Hongxu Lin Hongxu Lin - 1 year ago 107
Java Question

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++){
result = strings.toString();
return result;

Answer Source

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;

        if (add) result.append(readyToAdd);

    return result.toString();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download