Java program to print repeated characters from a string – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Wed, 11 Nov 2020 08:24:13 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg Java program to print repeated characters from a string – Programmerbay https://programmerbay.com 32 32 Java program to find duplicate characters in a string https://programmerbay.com/java-program-to-find-duplicate-characters-in-a-string/ https://programmerbay.com/java-program-to-find-duplicate-characters-in-a-string/#respond Tue, 07 Jul 2020 09:01:40 +0000 https://www.programmerbay.com/?p=4170 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

]]>
https://programmerbay.com/java-program-to-find-duplicate-characters-in-a-string/feed/ 0