Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print duplicate character from string in java

Tags:

java

string

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

like image 796
Shraddha Male Avatar asked Oct 12 '25 09:10

Shraddha Male


1 Answers

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.
like image 138
Keith Avatar answered Oct 15 '25 14:10

Keith