• Register
278 points
6 1

In this program, we need to find the duplicate characters in the string.

To find the duplicate character from the string, we count the occurrence of each character in the string. If count is greater than 1, it implies that a character has a duplicate entry in the string. 
import java.util.Scanner;

public class DuplicateCharacters {  
     public static void main(String[] args) 
     {  
    	 String string1;
		 int count; 
		 Scanner myObj = new Scanner(System.in);
    	 System.out.println("Enter String: "); 
    	 string1 = myObj.nextLine();
         
        //Converts given string into character array  
        char string[] = string1.toCharArray();  
     
        System.out.println("Duplicate characters in a given string is: ");  
        
		//Counts each character present in the string  
        for(int i = 0; i <string.length; i++) {  
            count = 1;  
            for(int j = i+1; j <string.length; j++) {  
                if(string[i] == string[j] && string[i] != ' ') {  
                    count++;  
                    //Set string[j] to 0 to avoid printing visited character  
                    string[j] = '0';  
                }  
            }  
            //A character is considered as duplicate if count is greater than 1  
            if(count > 1 && string[i] != '0')  
                System.out.println(string[i]);  
        }  
    }  
}  

Output:-

Enter String: 
Kodlogs is a learning website
Duplicate characters in a given string is: 
o
l
g
s
i
a
e
n

In the above code, first I defined a string. After that, two loops will be used to find the duplicate characters. Outer loop will be used to select a character and initialize variable count by 1. Inner loop will compare the selected character with rest of the characters present in the string. If a match found, it increases the count by 1 and set the duplicates of selected character by '0' to mark them as visited. After inner loop, if count of character is greater than 1, then it has duplicates in the string.

1 Comment

This is something I was looking for quite some time. Thanks for posting this.