Didart

Count Chars in a String

Nov 5th, 2021
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. import java.util.HashMap;
  2. import java.util.LinkedHashMap;
  3. import java.util.Map;
  4. import java.util.Scanner;
  5.  
  6. public class CountCharsInAString {
  7.     public static void main(String[] args) {
  8.         Scanner scanner = new Scanner(System.in);
  9.  
  10.         String text = scanner.nextLine();
  11.  
  12.         Map<Character, Integer> charsCount = new LinkedHashMap<>();
  13.  
  14.         for (char symbol : text.toCharArray()) {
  15.             if (symbol == ' ') {
  16.                 continue;
  17.             }
  18.             if (!charsCount.containsKey(symbol)) {
  19.                 charsCount.put(symbol, 1);
  20.             } else {
  21.                 int currentCount = charsCount.get(symbol);
  22.                 charsCount.put(symbol, currentCount + 1);
  23.             }
  24.         }
  25.  
  26.         charsCount.entrySet().forEach(entry -> System.out.println
  27.                 ( entry.getKey() + " -> " + entry.getValue()));
  28.  
  29.        
  30.   /*      for (Map.Entry<Character, Integer> entry : charsCount.entrySet()) {
  31.             System.out.println
  32.                     (entry.getKey() + " -> " + entry.getValue());
  33.         }      */
  34.     }
  35. }
  36.  
Advertisement
Add Comment
Please, Sign In to add comment