Advertisement
Guest User

Count Chars In A String

a guest
Nov 11th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.Scanner;
  4.  
  5. public class CountCharsInAString {
  6. public static void main(String[] args) {
  7. Scanner scanner = new Scanner(System.in);
  8. String sequence = scanner.nextLine();
  9. Map<Character, Integer> counts = new HashMap<>();
  10. String sequenceWithoutSpaces = sequence.replaceAll("\\s+", "");
  11. for (int i = 0; i < sequenceWithoutSpaces.length(); i++) {
  12. char currentChar = sequenceWithoutSpaces.charAt(i);
  13. if (!counts.containsKey(currentChar)) {
  14. counts.put(currentChar, 1);
  15. } else {
  16. int currentCount = counts.get(currentChar);
  17. counts.put(currentChar, currentCount + 1);
  18. }
  19. }
  20. for (Map.Entry<Character, Integer> entry : counts.entrySet()) {
  21. System.out.println(entry.getKey() + " -> " + entry.getValue());
  22. }
  23.  
  24. }
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement