Java program to find duplicate characters in a string

Share

The simple Java program finds duplicate characters in a given string and prints it as an output. There are two way to do it, first is by using nested loops and second one by sort method.

Suppose, we have given a string and asked us to dig out repeated characters and print over the screen. It is quite a tricky but its matter of fact how fast you build logic to find a solution.

Java program to find duplicate characters in a string using nested loops

Program:

public class RepeatedChar {
    public static void main(String[] args) {
        String str = "programmerbay";
        char[] ch1 = str.toLowerCase().toCharArray();
        int i, j, count;
        int len = ch1.length;
        System.out.println("Repeated characters in " + str);
        for (i = 0; i < len; i++) {
            count = 0;
            for (j = i + 1; j < len; j++) {
                if (ch1[i] == ch1[j]) {
                    count++;
                }
            }
            if (count == 1) System.out.print(ch1[i] + " ");
        }
    }
}

 

Output:

Repeated characters in programmerbay
r a m

Java program to find duplicate characters in a string using sort method and flags

Program :

public class DuplicateChar {
    public static void main(String[] args) {
        String str = "programmerbay";
        int flag = 0;
        char[] chrArr = str.toLowerCase().toCharArray();
        Arrays.sort(chrArr);
        System.out.println(" Duplicate Characters in the given String : ");
        for (int i = 0; i < chrArr.length - 1; i++) {
            if (chrArr[i] == chrArr[i + 1]) {
                if (flag == 0) {
                    System.out.println(chrArr[i]);
                }
                flag = 1;
            } else {
                flag = 0;
            }
        }
    }
}

Output:

 Duplicate Characters in the given String : 
a
m
r

This post was last modified on November 11, 2020

Sandeep Verma

Published by
Sandeep Verma
Tags: duplicates java java program Java program to find duplicate characters in a string Java program to print repeated characters from a string print repeated characters from a string program repeated characters