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.
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
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
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
std::count
is usually more efficient than a manual loop.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.
std::string
ObjectsA practical guide covering the most useful methods and operators for working with std::string
objects and their memory