javastringstringbuilder

how to delete duplicate character from a string


The problem asks me to write a method to delete the duplicate characters from the original string and return the new string.For example, the original string is abracadabra and the result should be abrcd.

I was thinking about using StringBuilder to delete the character, but something went wrong when I tried to run the code. can anyone help me fix it.

public static String eliminateDuplicates(String str){
    String result = "";
    StringBuilder strings = new StringBuilder(str);
    for(int i = 0; i<str.length(); i++){
        for(int j = 1; j<str.length();j++){
            if(str.charAt(i)==str.charAt(j)){
                strings.deleteCharAt(j);
            }
        }
    }
    result = strings.toString();
    return result;
}

Solution

  • Try this code, maybe your can optimize :

    public static String eliminateDuplicates(String source) {
        StringBuilder result = new StringBuilder();
        for (int i = 0, sLength = source.length(); i < sLength; i++) {
            char readyToAdd = source.charAt(i);
            boolean add = true;
    
            for (int j = 0; j < result.length(); j++) {
                if (readyToAdd == result.charAt(j)) {
                    add = false;
                    break;
                }
            }
    
            if (add) result.append(readyToAdd);
        }
    
        return result.toString();
    }