w3resource
Java Programming Exercies

Java String Exercises: Count and print all the duplicates in the input string

Java String: Exercise-51 with Solution

Write a Java program to count and print all the duplicates in the input string.

Sample Solution:

Java Code:

import java.util.*; 
public class Main 
{
    static final int MAX_CHARS = 256;
    static void CountCharacters(String str1, int[] ctr)
    {
       for (int i = 0; i < str1.length();  i++)
          ctr[str1.charAt(i)]++;
    }
    static void showDuplicates(String str1)
    {
      int ctr[] = new int[MAX_CHARS];
      CountCharacters(str1, ctr);
      for (int i = 0; i < MAX_CHARS; i++)
        if(ctr[i] > 1)
            System.out.printf("%c  appears  %d  times\n", i,  ctr[i]);
    }
    public static void main(String[] args)
    {
        String str1 = "w3resource";
		System.out.println("The given string is: "+str1);
		System.out.println("The duplicate characters and counts are: ");
        showDuplicates(str1);
    }
}

Sample Output:

The given string is: w3resource
The duplicate characters and counts are: 
e  appears  2  times
r  appears  2  times

Pictorial Presentation:

Java String Exercises: Count and print all the duplicates in the input string.

Flowchart:

Flowchart: Java String Exercises - Count and print all the duplicates in the input string

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to find lexicographic rank of a given string.
Next: Write a Java program to check if two given strings are rotations of each other.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming