...

/

Removing Duplicates in a String

Removing Duplicates in a String

Learn how to remove duplicates in a string using recursion.

What does removing duplicates mean?

When given a string that has repeating adjacent characters, we only want to keep one of each character. To do this, we must eliminate the repeating characters.

The illustration below shows this process.

Implementing the code

The code below shows how to do this with recursion. First, let’s see the code, and then we will go on to its explanation.

Try the code by changing the value of text to see how it works with other strings.

Press + to interact
class RemoveDuplicatesClass {
private static String remDuplicates(String text) {
if (text.length() == 1) {
return text;
}
if (text.substring(0,1).equals(text.substring(1,2))) {
return remDuplicates(text.substring(1));
}
else {
return text.substring(0,1) + remDuplicates(text.substring(1));
}
}
public static void main( String args[] ) {
String input1 = "Helloo";
String input2 = "Thiss iiss aa teesstt";
System.out.println( "Original string: " + input1);
String output = remDuplicates(input1);
System.out.println("String after: " + output);
}
}

Understanding the code

The recursive code can be broken down into two parts: the recursive method and the main method where ...