Java program to find all duplicate characters in a string


The duplicate characters in a string are those that occur more than once. These characters can be found using a nested for loop.

Problem Statement

Given a Java program to find the duplicate character in a given string.

Input

String = Tutorialspoint

Output

Duplicate Characters in above string are: t o i 

In the above string, t o i are duplicate characters as it occurs more than once.

Approach to find all duplicate characters in a string

Below are the steps to find all duplicate characters in a string −

  • Step 1: Convert the input string to a character array.
  • Step 2: Use a nested loop to compare each character with the remaining characters in the array.
  • Step 3: If a match is found, print the duplicate character.
  • Step 4: Use a break statement to exit the inner loop once a duplicate is found to avoid printing duplicates multiple times.
  • Step 5: Continue the process until all characters in the string have been checked.

Example

A program that demonstrates this is given as follows.

public class Example {
    public static void main(String argu[]) {
        String str = "beautiful beach";
        char[] carray = str.toCharArray();
        System.out.println("The string is:" + str);
        System.out.print("Duplicate Characters in above string are: ");
        for (int i = 0; i < str.length(); i++) {
            for (int j = i + 1; j < str.length(); j++) {
                if (carray[i] == carray[j]) {
                    System.out.print(carray[j] + " ");
                    break;
                }
            }
        }
    }
}

Output

The string is:beautiful beach
Duplicate Characters in above string are: b e a u

Code Explanation

Now let us understand the above program.

First, the string str is defined. Then, str.toCharArray() converts the string into a sequence of characters. The original string is displayed. The code snippet that demonstrates this is given as follows −

String str = "beautiful beach";
char[] carray = str.toCharArray();
System.out.println("The string is:" + str);

The duplicate characters are found in the string using a nested for loop. Then these characters are displayed. The code snippet that demonstrates this is given as follows.

System.out.print("Duplicate Characters in above string are: ");
for (int i = 0; i < str.length(); i++) {
   for (int j = i + 1; j < str.length(); j++) {
      if (carray[i] == carray[j]) {
         System.out.print(carray[j] + " ");
         break;
      }
   }
}

Updated on: 10-Jul-2024

43K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements