import java.util.*;
public class DuplicateCharacters {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner s = new Scanner(System.in);
        System.out.println("Enter String: ");
        String str = s.nextLine();
        for(int i=0;i<str.length()-1;i++)
        {
            for(int j=i+1;j<str.length();j++)
            {
            if(str.charAt(i)==str.charAt(j))
            {
                System.out.print(str.charAt(j));
            }
            }
        }
    }
}
My code works for string contains 2 duplicate character only ..
e.g. suppose input= india it prints i but when input aaa , output = a a a..it should print a once only
Attempt to put every newly read character into a Set<Character>. If adding to the set returns false, then add it to a set tracking all repeat characters. Here's pseudocode for it:
Set<Character> uniqueChars = new HashSet<Character>();
Set<Character> repeats = new HashSet<Character>();
for(int i = 0; i < str.length() - 1; i++) {
    if (!uniqueChars.add(str.charAt(i)) {
        repeats.add(str.charAt(i));
    }
}
// now loop through the repeats set and print out each one.
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With