JavaLearner1 JavaLearner1 - 6 months ago 21
Java Question

Removing duplicate character in string using StringBuilder

I am trying to compare 2 strings and remove the duplicates using StringBuilder..but when i run this code..it removes the first duplicate found and then comes out of the loop...not removing the second one..

String name1 = "alpha";
String name2 = "delta";

name1 = name1.toLowerCase();
name2 = name2.toLowerCase();

StringBuilder sb1 = new StringBuilder(name1);
StringBuilder sb2 = new StringBuilder(name2);

for(int i=0; i<sb1.length();i++)
{
for(int j=0; j<sb2.length(); j++)
{
if(sb1.charAt(i) == sb2.charAt(j))
{
name1 = sb1.deleteCharAt(i).toString();
name2 = sb2.deleteCharAt(j).toString();
}
}
}
System.out.println(name1);
System.out.println(name2);


Output:

lpha
delt

Answer

Your code is not working because every time when you delete a character from the StringBuilder the length of StringBuilder decreases. And also the index of all the characters changes.

So don't remove characters directly in the loop, but replace the character you want to remove with some other sign (here 0) and then remove it or just don't print the 0.

Try the following code:

String name1 = "alpha";
String name2 = "delta";

name1 = name1.toLowerCase();
name2 = name2.toLowerCase();


StringBuilder sb1 = new StringBuilder(name1);
StringBuilder sb2 = new StringBuilder(name2);

for(int i=0; i<sb1.length();i++)
{
for(int j=0; j<sb2.length(); j++)
{

    if(sb1.charAt(i) == sb2.charAt(j))
    {
        sb1.replace(i, i+1, "0");
        sb2.replace(j,j+1,"0");
    }
}
}

String s = sb1.toString();
String t = sb2.toString();
for(int i=0;i<s.length();i++){
    if(s.charAt(i)!='0'){
    System.out.print(s.charAt(i));
    }
}
    System.out.println();
for(int i=0;i<s.length();i++){
    if(t.charAt(i)!='0'){
    System.out.print(t.charAt(i));
    }
} 

Also no need to convert StringBuilder to String every time in the for loop.

Comments