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.
1 | public class DuplicateCharacters { |
3 | public static void main(String[] args) { |
5 | String str = new String("Sakkett"); |
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]); |
Output:
Duplicate characters are:
k
t