How to Remove Duplicates from a String in Java?
Last Updated :
12 Feb, 2024
Working with strings is a typical activity in Java programming, and sometimes we need to remove duplicate characters from a string. In this article we have given a string, the task is to remove duplicates from it.
Example
Input: s = “geeks for geeks”
Output: str = “geks for”
Remove Duplicates From a String in Java
This approach uses a for loop to check for duplicate characters, the code checks for the presence of spaces and non-space characters. If the character is not a space, the code executes further to check whether the character is already there in the ans string or not, this is checked using the indexOf() method, which returns the first occurrence index of the character if the character is present, else returns -1. If the character is not there it gets added to the ans string. The final answer is trimmed using the trim() method to remove extra leading and trailing spaces.
Below is the implementation of removing duplicates from a String:
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
String s = "geeks for geeks" ;
String ans = "" ;
for ( int i = 0 ; i < s.length(); i++) {
char temp = s.charAt(i);
if (temp != ' ' ) {
if (ans.indexOf(temp) <= - 1 ) {
ans = ans + temp;
}
}
else {
ans = ans + ' ' ;
}
}
ans = ans.trim();
System.out.println( "Output : " + ans);
}
}
|
Share your thoughts in the comments
Please Login to comment...