TacoB2018
TacoB2018

Reputation: 33

Remove duplicates in a String and create a new String

I am new to Java and am trying to create a method that will allow me to remove duplicate characters in a string and create a new string with all the consecutive occurrences of the same character turned into a single character. For example, string fffggghhh would return as fgh. I have provided my code below but I am receiving an index out of range error with the length of the string that I input. For example when testing this method and entering AA as my string, I receive an index out of range 2 error.

public String DuplicatesTEST(String s) {
    StringBuilder result = new StringBuilder();
    for (int i = 1; i <= s.length(); i++) {
        char curr = s.charAt(i);
        char prev = s.charAt(0);
        if (curr != prev) {
            result.append(prev);
        } else if (curr == prev)
            prev = curr;
    }
    return result.toString();
}

Upvotes: 0

Views: 2462

Answers (3)

janith1024
janith1024

Reputation: 1042

Behavior of Data structure Set is not containing duplicates, so use Set to remove duplicates.
Try something like this:

public String DuplicatesTEST(String s) {
    Set<Character> set = new HashSet<>();
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        set.add(s.charAt(i));
    }
    set.forEach(result::append);
    return result.toString();
}

for fffggghhhff input this return fgh.

If you want to remove duplicates with a block above solution not help then I did small change to your implementation:

public String DuplicatesTEST(String s) {
    StringBuilder result = new StringBuilder();
    if (s != null && !s.isEmpty()) {
        char first = s.charAt(0);
        for (int i = 1; i < s.length(); i++) {
            if (first != s.charAt(i)) {
                result.append(first);
                first = s.charAt(i);
            }
        }
        result.append(first);
    }
    return result.toString();
}

for fffggghhhff input this return fghf.

Upvotes: 2

user15613375
user15613375

Reputation:

You can transform your method to recursive and use regexp. This greatly simplifies your code.

Try it online!

public static String removeDuplicates(String str) {
    if (str.equals(str = str.replaceAll("(.)\\1", "$1")))
        return str;
    else
        return removeDuplicates(str);
}
public static void main(String[] args) {
    System.out.println(removeDuplicates("aaaaaaa"));     // a
    System.out.println(removeDuplicates("fffggghhh"));   // fgh
    System.out.println(removeDuplicates("fffggghhhff")); // fghf
}

Explanation:

  • regexp (.)\\1 - any character followed by the same character;
    • regexp $1 - replace with a character from the 1st group, i.e. the same character;
  • str = str.replaceAll(...) - removes all duplicates and replaces current string;
  • str.equals(...) - checks equality of the current string with itself, but without duplicates.

See also: Remove a pair of chars in a string next to each other

Upvotes: 1

R4V
R4V

Reputation: 1

Strings are 0 based Index.

As per your input, If duplicate characters are consecutive orders then you can store first character from your input string into result StringBuilder.

Also, in your code, prev always stars at 0 which is wrong. You need to keep increment it too.

Here is is fixed version of your code:

public static String DuplicatesTEST(String s) {
    StringBuilder result = new StringBuilder();
    result.append(s.charAt(0));
    for (int i = 1; i < s.length(); i++) {
        char prev = s.charAt(i);
        char curr = s.charAt(i - 1);
        if (curr != prev || i == 0) {
            result.append(prev);
        }
        else if (curr == prev) {
            prev = curr;
        }
    }
    return result.toString();
}

Upvotes: 0

Related Questions