Java: 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 duplicates in the input string.
Visual Presentation:
Sample Solution:
Java Code:
// Importing necessary Java utilities.
import java.util.*;
// Define a class named Main.
public class Main {
// Constant to represent the maximum number of characters (ASCII).
static final int MAX_CHARS = 256;
// Method to count the occurrences of each character in the string.
static void CountCharacters(String str1, int[] ctr) {
// Loop through the characters in the string.
for (int i = 0; i < str1.length(); i++)
ctr[str1.charAt(i)]++; // Increment the count for the corresponding character.
}
// Method to display the duplicate characters along with their counts.
static void showDuplicates(String str1) {
int ctr[] = new int[MAX_CHARS]; // Array to store character counts.
CountCharacters(str1, ctr); // Count the characters in the string.
// Loop through all ASCII characters.
for (int i = 0; i < MAX_CHARS; i++) {
// If the count of a character is greater than 1, it's a duplicate character.
if (ctr[i] > 1)
// Print the duplicate character and its count.
System.out.printf("%c appears %d times\n", i, ctr[i]);
}
}
// Main method to execute the program.
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); // Display the duplicate characters and their counts.
}
}
Sample Output:
The given string is: w3resource The duplicate characters and counts are: e appears 2 times r appears 2 times
Flowchart:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/string/java-string-exercise-51.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics