fork download
  1. #include<iostream>
  2. #include<string>
  3. #include<cctype>
  4.  
  5. std::string to_lower(std::string s)
  6. {
  7. std::string result;
  8. for (auto ch : s)
  9. result += std::tolower(ch);
  10. return result;
  11. }
  12.  
  13. std::string clean(std::string s)
  14. {
  15. std::string result;
  16. for (auto ch : s)
  17. if (isalpha(ch))
  18. result += ch;
  19.  
  20. return result;
  21. }
  22.  
  23. std::string process(std::string s)
  24. {
  25. return to_lower(clean(s));
  26. }
  27.  
  28. unsigned as_index(char ch)
  29. {
  30. return ch - 'a';
  31. }
  32.  
  33. std::string get_line(std::string prompt)
  34. {
  35. std::string line;
  36.  
  37. std::cout << prompt;
  38. std::getline(std::cin, line);
  39.  
  40. return line;
  41. }
  42.  
  43. int main()
  44. {
  45. const unsigned counts_size = 26;
  46. int counts[counts_size] = {}; // initialize all elements to 0.
  47.  
  48. std::string raw_text = get_line("Enter a string:\n> ");
  49. std::string text = process(raw_text);
  50.  
  51. for (unsigned i = 0; i < text.length(); ++i)
  52. ++counts[ as_index(text[i]) ];
  53.  
  54. for (unsigned i = 0; i < text.length(); ++i)
  55. std::cout << text[i] << ": " << counts[ as_index(text[i]) ] << '\n';
  56. }
Success #stdin #stdout 0s 3236KB
stdin
Welcome to hell!~@#1
stdout
Enter a string:
> w: 1
e: 3
l: 3
c: 1
o: 2
m: 1
e: 3
t: 1
o: 2
h: 1
e: 3
l: 3
l: 3