Java Program to Find the Duplicate Characters in a String

JavaCampus InterviewServer Side ProgrammingProgramming

In this article, we will understand how to find the duplicate characters in a string. String is a datatype that contains one or more characters and is enclosed in double quotes(“ ”).

Below is a demonstration of the same −

Suppose our input is

Input string: Java Programming

The desired output would be

The duplicate characters in the string are: a a r g m

Algorithm

Step 1 - START
Step 2 - Declare a string namely input_string, a char array namely character_array.
Step 3 - Define the values.
Step 4 - Convert the string to character array.
Step 5 – Iterate over the character_array twice with ‘i’ and ‘j’ values. Using an if-confition, check if ‘i’th value matches with the ‘j’th value. If yes, it’s a duplicate. Store the value.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

public class Demo {
   public static void main(String argu[]) {
      String input_string = "Java Programming";
      System.out.println("The string is defined as: " + input_string);
      char[] character_array = input_string.toCharArray();
      System.out.print("\nThe duplicate characters in the string are: ");
      for (int i = 0; i < input_string.length(); i++) {
         for (int j = i + 1; j < input_string.length(); j++) {
            if (character_array[i] == character_array[j]) {
               System.out.print(character_array[j] + " ");
               break;
            }
         }
      }
   }
}

Output

The string is defined as: Java Programming

The duplicate characters in the string are: a a r g m

Example 2

Here, we encapsulate the operations into functions exhibiting object-oriented programming.

public class Demo {
   static void duplicate_characters(String input_string){
      char[] character_array = input_string.toCharArray();
      System.out.print("\nThe duplicate characters in the string are: ");
      for (int i = 0; i < input_string.length(); i++) {
         for (int j = i + 1; j < input_string.length(); j++) {
            if (character_array[i] == character_array[j]) {
               System.out.print(character_array[j] + " ");
               break;
            }
         }
      }
   }
   public static void main(String argu[]) {
      String input_string = "Java Programming";
      System.out.println("The string is defined as: " + input_string);
      duplicate_characters(input_string);
   }
}

Output

The string is defined as: Java Programming

The duplicate characters in the string are: a a r g m
raja
Updated on 30-Mar-2022 07:00:23

Advertisements