Last Updated:

How to remove duplicate characters from a string in java

string in java

In this article, we will learn how to check words for duplicate characters, as well as replace and delete duplicates found. We will do this with the help of a special algorithm, which is now implemented in Java.

Remove duplicate characters from a string. Theory

 

Today we implement an interesting method that takes a string as input, for example, "jjjj", and outputs "j". To do this, we will not use third-party libraries, but will do everything in pure Java.

We implement the algorithm for removing repeating characters in a string in the deleteDuplicates (String input) method, which takes a string with duplicates as a parameter and returns a new line without duplicates.

The essence of the algorithm is that we go through each character of the line and check whether it is a duplicate of the already found symbol. If it is, then insert 0 instead. This continues until we loop through the entire line to the end. After the loop, a method is called that creates a string from an array of characters, skipping zero-based characters. This method will work even if the input string contains more than one repeating character. Such an algorithm is a brute force algorithm (the so-called brute force or the method of "brute force").

How to remove duplicate characters from a string. Practice

 

The following is a method for removing duplicate characters from an input string:

Note that here you can do without a variable, but for clarity I decided to leave.position

Now let's run it and see what happened:

As you can see, the method returned an empty string unchanged, since its length is less than 2.

Here's an easy way to check words for duplicate characters, replace and delete duplicates found.