Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe