Monica Hübner
Monica Hübner

Reputation: 279

How to delete duplicate characters in a string?

I have a method that supposed to delete all the dups from string passed inside it. I can print the dups, how can I delete them in the original string ? Say, 'miami' will need to be 'mia' when it will return. Thanks.

  public static String removeDups( String str1){

        char[] str = str1.toCharArray();
        if (str == null) return null;
        int len = str.length;
        if (len < 2) return new String(str);

        char[] newStr = new char[len+1];  
        int copyLength = 0; 

        for ( int i = 1 ; i < len; i++){

            for( int j=0; j< i; j++){

                if ( str[i] == str[j]){
                    System.out.println(" str[i] == str[j] = "+ str[i] + " , "+str[j]);
                    break; 
                }

            }

        }

        return new String(str); 
    }

Upvotes: 0

Views: 249

Answers (5)

Hemant Nigam
Hemant Nigam

Reputation: 31

You can also use Arraylist to store the unique characters:

public static String removeDups( String str1){
ArrayList<Character> set=new ArrayList<Character>();
    char[] str=str1.toCharArray();
    for(int i=0;i<str.length;i++)
     {
        if(!set.contains(str[i])){
            set.add(str[i]);
        }
     }
    for(char e:set)
    {
        System.out.print(e);
    }    
}

Upvotes: 1

maja
maja

Reputation: 18044

Your loop seems to be a bit strange.

char[] str = str1.toCharArray();
int len = str.length;
if (str == null || len  < 2) return null;

char[] newStr = new char[len+1];  
int newStrLength = 0;  

for( int i = 1; i < len; i++ ){  //Iterate complete string
    for(  int j=0; j < i; j++ ){  //Iterate the already-finished part
        if( str[i] == str[j] ) 
            break; 
        }
        newStr[newStrLength++] = str[i];
    }
}
newStr[newStrLength] = 0;

In this example I make a completly new string and don't alter the original one. It makes the code clearer to read.

Alternatively you could take a look at this question which has some more efficient answers.

Upvotes: 0

Shar1er80
Shar1er80

Reputation: 9041

I found this to be easier using a StringBuilder rather than a String

EDIT

This can also be done with a combination of StringBuilder and regex

Regex Pattern breakdown:

 (.)    --> matches any character and puts in group 1. 
 ?=     --> this is called a positive lookahead. 
 ?=.*\\1  --> positive lookahead of zero or more characters for the first group

Code Sample:

public static void main(String[] args) throws Exception {
    System.out.println(removeDuplicates("miamimiamimiami"));
    System.out.println(removeDuplicatesRegex("miamimiamimiami"));
}

public static String removeDuplicates(String input){
    StringBuilder data = new StringBuilder(input);
    for (int i = 0; i < data.length(); i++) {
        String character = String.valueOf(data.charAt(i));
        int dupIndex = data.indexOf(character, i + 1);
        while (dupIndex != -1) {
            data.deleteCharAt(dupIndex);
            dupIndex = data.indexOf(character, i + 1);
        }
    }

    return data.toString();
}

public static String removeDuplicatesRegex(String input) {

    return new StringBuilder(
            new StringBuilder(input)
                    .reverse()
                    .toString()
                    .replaceAll("(.)(?=.*\\1)", ""))
            .reverse().toString();
}

Results:

mia
mia

Upvotes: 2

Rajesh
Rajesh

Reputation: 2155

Remove all duplicate chars in a String:

public static String removeDuplicates(String str1) {

    if (str1 == null)
        return null;

    char[] str = str1.toCharArray();

    int len = str.length;

    if (len < 2)
        return str1;

    char temp = str[0];

    for (int i = 1; i < len; i++) {

        if (temp != 0)
            for (int j = i; j < len; j++)
                if (temp == str[j])
                    str[j] = 0;

        temp = str[i];
    }

    int i = 0;

    char[] str2 = new char[len];

    for (char c : str)
        if (c != 0)
            str2[i++] = c;

    return (new String(str2)).trim();
}

Upvotes: 1

FredK
FredK

Reputation: 4084

Here's another option:

  StringBuffer buf = new StringBuffer( originalString);
  int len = str.length();
  for (int i = 0; i < len; i++) {
     char c = buf.charAt( i );
     for (int j = len - 1; j > i; j--) {
        if ( buf.charAt( j ) == c ) {
           buf.deleteCharAt( j );
           len--;
        }
     }
  }

Upvotes: 1

Related Questions