Java Program to find out the duplicate characters in a string


April 1, 2022, Learn eTutorial
1009

Here we are explaining how to write a java program to find out the duplicate characters in a string.

How to implement the java program to find out the duplicate characters in a string?

First, we have to declare the class DC. Then open the main function. Declare the string variables str1 and assign value for it. Declare a character array and convert the string str1 into character. Then by using a nested for loop check any duplicate characters are there. If found then increment the count variable c by one and change the position of the character to '1'.Then we will display the duplicate character by checking the condition if i>0 and ch!='1'.

How to convert the string into a character array in java?

We can convert a string into a character array by using the method toCharArray(). The syntax of toCharArray() is shown below.

public char[] toCharArray().

It returns a character array. The length of the character array is same as the length of the string.

ALGORITHM

STEP 1: Declare the class DC with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Declare the string variable str1 and assign some value to it.

STEP 4: convert the string str1 to an array s[] by using toChaArray() method.

STEP 5: By using a for loop set i=0, check i

STEP 6: set c=1.

STEP 7: By using another for loop set j=i+1,check the condition j

STEP 8: Check if s[i]=s[j]  and s[j]!=' '' then incremnet c by one.

STEP 9: Set s[j] to 1. Increment j by one and  repeat step 7.

STEP 10: Check if c>1 and s[i]!='1' then display s[i]

STEP 11:Incremnet i by one and  repeat step 5.

 

Java Source Code

                                          public class DC {
    public static void main(String[] args) {
        String str1 = "My name is siril";
        int c;

        //Convert the string to array  
        char s[] = str1.toCharArray();

        System.out.println("Duplicate characters in the string: ");

        for (int i = 0; i < s.length; i++) {
            c = 1;
            for (int j = i + 1; j < s.length; j++) {
                if (s[i] == s[j] && s[i] != ' ') {
                    c++;
                    //Set str1[j] to 1
                    s[j] = '1';
                }
            }

            if (c > 1 && s[i] != '1')
                System.out.println(s[i]);
        }
    }
}
                                      

OUTPUT

Duplicate characters in the string: 
i
s