-->

9/19/2019

Write a Java Program to find the duplicate characters in a string.

In this program, we have created a string variable str and initialized an integer count with zero.
Then, we have created a character array to convert our string variable to the character. With the help of for loop, we are performing a comparison between different character at different indexes.
If two character of consecutive index matches, then it will print that character and the counter will be incremented by 1 after each iteration.
1public class DuplicateCharacters {
2          
3          public static void main(String[] args) {
4                   // TODO Auto-generated method stub
5                  String str = new String("Sakkett");
6                  int count = 0;
7                  char[] chars = str.toCharArray();
8                  System.out.println("Duplicate characters are:");
9                  for (int i=0; i<str.length();i++) {
10                              for(int j=i+1; j<str.length();j++) {
11                                         if (chars[i] == chars[j]) {
12                                                    System.out.println(chars[j]);
13                                                    count++;
14                                                    break;
15                                          }
16                               }
17                   }
18           }
19 
20}

Output:
Duplicate characters are:
k
t
NEXT ARTICLE Next Post
PREVIOUS ARTICLE Previous Post
NEXT ARTICLE Next Post
PREVIOUS ARTICLE Previous Post