Remove Repeated Characters from the String


 

Remove Repeated Characters from the String

In this java Tutorial Series, we are going to remove repeated characters from the string.

In this java Tutorial Series, we are going to remove repeated characters from the string.

Remove Repeated Characters from the String

In this we are going to remove repeated characters from the string. For this, we have allowed the user to enter the string. The class BufferedReader reads the string from the console. Then we have used the replaceAll((String.format("(.)(?<=(?:(?=\\1).).{0,%d}(?:(?=\\1).))" method that have removed all the repeated characters.

Here is the code:

import java.io.*;

public class RemoveRepeatedCharacters{
public static void main(String[]argsthrows Exception{
System.out.print("Enter the String : ");
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
String inputString = br.readLine();
System.out.println("Original String is: "+inputString);
inputString = inputString.replaceAll((String.format("(.)(?<=(?:(?=\\1).).{0,%d}(?:(?=\\1).))", inputString.length()))"");
System.out.println("New String is: "+inputString);
}
}

Output:

Enter the String : Hello World
Original String is: Hello World

New String is: Helo Wrd

Ads