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. An example of this is given as follows −

String = Apple

In the above string, p is a duplicate character as it occurs more than once.

A program that demonstrates this is given as follows.

Example

Live Demo

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

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;
      }
   }
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 08-Sep-2023

35K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements