Manipulating std::string Objects

Count Character Occurrences

How can I count the number of occurrences of a character in a std::string?

Abstract art representing computer programming

Counting the number of occurrences of a character in a std::string can be done using various methods in C++. Here, we'll explore some of the most common techniques.

Using a Loop

A simple way to count occurrences is by using a loop to iterate through each character in the string. For example:

#include <iostream>
#include <string>

int main() {
  std::string Text{"Hello, World!"};
  char Character{'l'};
  int Count{0};

  for (const char& c : Text) {
    if (c == Character) {
      ++Count;  
    }
  }

  std::cout << "Number of '" << Character
    << "' in \"" << Text << "\": " << Count;
}
Number of 'l' in "Hello, World!": 3

Using std::count

The <algorithm> header provides the std::count function, which simplifies the process. For example:

#include <iostream>
#include <string>
#include <algorithm>

int main() {
  std::string Text{"Hello, World!"};
  char Character{'l'};

  int Count = std::count(
    Text.begin(), Text.end(), Character
  );  

  std::cout << "Number of '" << Character
    << "' in \"" << Text << "\": " << Count;
}
Number of 'l' in "Hello, World!": 3

Using a Map for Multiple Characters

If you need to count multiple characters, consider using a map to store the counts. For example:

#include <iostream>
#include <string>
#include <map>

int main() {
  std::string Text{"Hello, World!"};
  std::map<char, int> Counts;

  for (const char& c : Text) {
    ++Counts[c];  
  }

  for (const auto& Pair : Counts) {
    std::cout << "Number of '" << Pair.first
              << "': " << Pair.second << "\n";
  }
}
Number of 'H': 1
Number of 'e': 1
Number of 'l': 3
Number of 'o': 2
Number of ',': 1
Number of ' ': 1
Number of 'W': 1
Number of 'r': 1
Number of 'd': 1
Number of '!': 1

Considerations

  • Performance: For large strings, using std::count is usually more efficient than a manual loop.
  • Case Sensitivity: These methods are case-sensitive. To perform a case-insensitive count, you can convert the string to a uniform case before counting.

By using these techniques, you can easily count the number of occurrences of a character in a std::string.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved