We write a program to find duplicate characters in a string in java. For example, consider a string “nut cutter“, duplicate characters in it are : u: 2, t : 3.
Program Approach:
First, we created a string variable and take the user input for a string to compare with. And initialize a variable num to keep the number of counts. Then we convert the string variable to characters by creating a character array. Then with iteration(for loop), we compare the two characters and if the character of the compared index is matched, then we display that character with the increase of num with each iteration.
The for loop will continue till the length of the entered string is finished.
Java program of string to check duplicate characters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | import java.util.Scanner; public class FindDuplicateCharacters { public static void main(String[] args) { String str; int num = 0; Scanner in = new Scanner(System.in); //Get input String System.out.println("Enter a string: "); str = in.nextLine(); /*//if you want to define the string in a program //follow the below code and remove above String str = new String("simple2code.com");*/ char[] chars = str.toCharArray(); System.out.println("Duplicate characters are:"); for (int i=0; i<str.length();i++) { for(int j=i+1; j<str.length();j++) { if (chars[i] == chars[j]) { System.out.println(chars[j]); num++; break; } } } } } |
The output of duplicate characters in java
Enter a string:
simple2code.com
Duplicate characters are:
m
e
c
o