Java Program To Find Repeated Characters Of String
Chapter:
Miscellaneous
Last Updated:
15-08-2023 14:22:42 UTC
Program:
/* ............... START ............... */
import java.util.HashMap;
import java.util.Map;
public class RepeatedCharacters {
public static void main(String[] args) {
String input = "Hello, World!";
Map<Character, Integer> charFrequency = new HashMap<>();
for (char c : input.toCharArray()) {
if (Character.isLetter(c)) {
c = Character.toLowerCase(c); // Ignore case
charFrequency.put(c, charFrequency.getOrDefault(c, 0) + 1);
}
}
System.out.println("Repeated characters in the string:");
for (Map.Entry<Character, Integer> entry : charFrequency.entrySet()) {
if (entry.getValue() > 1) {
System.out.println("'" + entry.getKey() + "' - " + entry.getValue() + " times");
}
}
}
}
/* ............... END ............... */
Output
Repeated characters in the string:
'l' - 3 times
'o' - 2 times
Notes:
-
Replace the input variable with the string you want to analyze. The program uses a HashMap to store the frequency of characters in the input string and then iterates over the map to find and print the repeated characters along with their frequency. The program ignores non-letter characters and considers the characters in a case-insensitive manner.
- We create a HashMap called charFrequency to store the frequency of characters.
- For loop prints out the repeated characters along with their frequency. It iterates through the charFrequency map and checks if the frequency is greater than 1 before printing the character and its frequency.