2

I am working with my program and I need to remove repeated characters from a string given to me by the user. I referenced other questions, but they are all using StringBuilder to remove duplicates. However, is there any way to remove duplicates without turning the string into an array, using StringBuilder and Set?

I haven't learnt those yet, so I don't understand them very well. Could I get some help?

For example, if user types in happyrolling the result should be hapyroling.

4
  • 1
    Repeated words or repeated characters?? Commented Aug 23, 2013 at 22:30
  • 1
    Your example is unfortunate, because all the letters are never repeated later on. Are duplicates removed if they appear immediately after or anywhere later in the string? Commented Aug 23, 2013 at 22:43
  • You'll have to break down the String into chars eventually for processing it as a String is actually nothing more than a collection of chars Commented Aug 23, 2013 at 22:49
  • Oh i mean i want to remove repeated characters in word. So, there is no way to do this without breaking down every characters in string. Am i understand in right way? Commented Aug 24, 2013 at 8:42

2 Answers 2

4

It seems from your example you want to remove repeated characters (not words).

You can use regex to find the repeats and remove them:

str = str.replaceAll("(.)\\1+", "$1");

This regex captures every character but only matches when followed by the same character by using a back reference to the captured group. The replacement is the captured character, so for example "xx" is replaced by "x"

Sign up to request clarification or add additional context in comments.

2 Comments

What about something like "aba", wouldn't the expected output be "ab"?
@arshajii I don't think so, but you're right - all letters are unique - it's a bad example. if that is the case it can also be done using replaceAll()
0

Somehow you need to convert the string into character array. String is immutable in Java, so if you want to do any type of operation in the String, either you have to convert it to charArray or you have to use StringBuilder to create new String. You can keep track of the used character using hashmap.

public String removeDuplicates(String str){
    char[] array = str.toCharArray();
    char ch;
    int k = 0;
    HashMap<Character, Integer> hMap = new HashMap();
    for(int i = 0; i < str.length(); i++){
        ch = array[i];
        if(hMap.get(ch) == null){
            array[k++] = ch;
            hMap.put(ch, 1);
        }
    }
    return new String(array, 0, k);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.