Open In App

How to Remove Duplicates from a String in Java?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Java Program to Remove Duplicates
// From a String
import java.util.*;
  
// Driver Class
class GFG {
    public static void main(String[] args)
    {
        String s = "geeks for geeks";
        String ans = "";
        // using a for loop to iterate in the string
        for (int i = 0; i < s.length(); i++) {
            char temp = s.charAt(i);
            // checking for space in the string
            if (temp != ' ') {
                // checking if the character is already
                // present in the new String if not adding
                // the character to the new string
                if (ans.indexOf(temp) <= -1) {
                    ans = ans + temp;
                }
            }
            // if there is a space adding that to the string
            else {
                ans = ans + ' ';
            }
        }
        // using trim function to remove if any leading and
        // trailing space are there
        ans = ans.trim();
        System.out.println("Output : " + ans);
    }
}


Output

Output : geks for


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads