Removing duplicate values from StringBuffer

3.1k views Asked by At

I have a StringBuffer which contains duplicates value like the one shown on the left hand side of the example and want to convert it to the one showm on right. Two cases are shown below

{1,1,1,2,2,} to `{1,2}` 

{a,a,a,b,c,c,c,} to {a,b,c}

Please also note that the content and size of StringBuffer is not fixed. I want to solve this problem just by string manipulation.

2

There are 2 answers

0
River On BEST ANSWER

Well here's a solution that works for duplicates that are not adjacent. It is a bit clunky though...

//Deletes all extra occurrences of String x(which can just be a single character)
public static StringBuffer removeDuplicateOf(StringBuffer s, String x){
    while(s.indexOf(x) != s.lastIndexOf(x))
        s.deleteCharAt(s.lastIndexOf(x));
    return s;
}

Note, if you didn't know which items were duplicated, you'd have to call this on every item in your StringBuffer. (Well once per unique item in your StringBuffer.)

For example you could do:

StringBuffer s = new StringBuffer("1,2,4,8,16,1,2,4,6,8,10,12,14,16,");
s.removeDuplicateOf(s, "1,");

This would avoid removing the "1" from "16", "10", etc. while still removing the other occurence of "1".

3
Adam On
String s = "1,1,1,2,2";
System.out.println(s.replaceAll("(.)\\1+", "$1"));