Followers

Showing posts with label Counts the occurrences of each character in a given string. Show all posts
Showing posts with label Counts the occurrences of each character in a given string. Show all posts

Wednesday, August 16, 2023

C++ program that counts the occurrences of each character in a given string

 

Here's a C++ program that counts the occurrences of each character in a given string:

cpp
#include <iostream> #include <map> int main() { std::string inputString; std::cout << "Enter a string: "; std::getline(std::cin, inputString); std::map<char, int> characterCount; for (char character : inputString) { // Ignore whitespace characters if (!std::isspace(character)) { characterCount[character]++; } } std::cout << "Character occurrences:" << std::endl; for (const auto& entry : characterCount) { std::cout << "'" << entry.first << "': " << entry.second << " times" << std::endl; } return 0; }

Explanation:

  1. 1. The program uses a std::map named characterCount to store the counts of each character in the input string.
  2. 2. The program first takes an input string from the user using std::getline, which allows for reading a complete line of text.
  3. 3. The program then iterates through each character in the input string.
  4. 4. Inside the loop, whitespace characters (like spaces or tabs) are ignored using the std::isspace function.
  5. 5. The non-whitespace characters are inserted into the characterCount map, and their counts are incremented.
  6. 6. After processing all characters, the program prints out the occurrences of each character.
  7. 7. The for loop iterates through the characterCount map and prints the character and its corresponding count.

For example, if the user inputs "hello world", the output might be:

cpp
Enter a string: hello world Character occurrences: 'h': 1 times 'e': 1 times 'l': 3 times 'o': 2 times 'w': 1 times 'r': 1 times 'd': 1 times

In this example, the program counts and displays the occurrences of each character in the input string, while ignoring whitespace characters.