fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public void charCount(String sentence) {
  11. // Convert the sentence to lower case.
  12. String l = sentence.toLowerCase();
  13.  
  14. // Create a set of separators
  15. Set<Character> separators = new HashSet<>(Arrays.asList(' ', '!', '?', ';', '.', '/', '~', '(', ')', '`', '-', '"'));
  16.  
  17. // Create a queue of characters in the sentence.
  18. Queue<Character> q = new LinkedList<>();
  19.  
  20. // Create a map to keep track of the number of characters.
  21. Map<Character, Integer> charMap = new HashMap<>();
  22.  
  23. // For each character in the string...
  24. for (int i = 0; i < l.length(); i++) {
  25. char c = l.charAt(i);
  26.  
  27. // If it is not a separator...
  28. if (!separators.contains(c)) {
  29. // And it is already in the map...
  30. if (charMap.containsKey(c)) {
  31. // Update the value in the map.
  32. charMap.put(c, charMap.get(c) + 1);
  33. } else {
  34. // Otherwise, add character to the map and enqueue the newly encountered char.
  35. charMap.put(c, 1);
  36. q.add(c);
  37. }
  38. }
  39. }
  40.  
  41. // For each character in the queue, print out its corresponding value in the map.
  42. for (Character outChar : q) {
  43. System.out.println(outChar + ": " + charMap.get(outChar));
  44. }
  45. }
  46.  
  47. public static void main(String[] args) {
  48. Ideone cc = new Ideone();
  49. cc.charCount("Count the, characters.");
  50. }
  51. }
  52.  
Success #stdin #stdout 0.15s 57844KB
stdin
Standard input is empty
stdout
c: 3
o: 1
u: 1
n: 1
t: 3
h: 2
e: 2
,: 1
a: 2
r: 2
s: 1