In C++, use std::count from the <algorithm> header to count how many times a character appears in a string: std::count(text.begin(), text.end(), 'a'). It returns the number of matching characters in the iterator range; it does not directly count a whole substring.
What std::count Does
std::count is a standard-library algorithm that examines a range and counts elements equal to a supplied value. A std::string is a sequence of characters, so its beginning and ending iterators provide the range to search. The algorithm compares each character with the value and returns the total number of matches.
The declaration is provided by <algorithm>. A typical program also includes <iostream> for input and output and <string> for the string type:
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string text = "banana";
int count = std::count(text.begin(), text.end(), 'a');
std::cout << count << '\n'; // 3
}
For this example, the characters at positions 1, 3, and 5 are 'a', so the result is 3. The function does not modify the string. It only reads the characters in the range, making it suitable when the original text must remain unchanged.
Counting a Character in a String
The usual form is std::count(first, last, value). For a string named text, text.begin() points to its first character and text.end() points just past its last character. Pass the character as a single-quoted character literal, such as 'x', rather than a double-quoted string literal such as "x".
Here is a small example that counts a comma in a line of data:
std::string row = "Mira,28,Oslo";
auto commas = std::count(row.begin(), row.end(), ',');
std::cout << commas; // 2
The auto declaration is useful because the algorithm returns an iterator difference type, commonly named difference_type, rather than promising a particular integer type such as int. For a short display example, assigning the result to an integer often works, but retaining the returned type with auto avoids an unnecessary conversion. The result is zero if the searched character is absent, and an empty string also produces zero.
Spaces and punctuation are ordinary characters in this operation. To count spaces, pass ' '; to count a question mark, pass '?'. A newline can be counted as '\n' if the string actually contains newline characters. Input functions that read only one word may stop at whitespace, so make sure the string contains the full text you intend to examine.
Using a Particular Range
The two iterators do not have to cover the entire string. If you want to inspect only part of it, supply iterators delimiting that part. For instance, std::count(text.begin() + 2, text.begin() + 6, 'a') examines the characters at indexes 2 through 5, because the second iterator is excluded. This half-open range convention—first included, last excluded—is used throughout the C++ standard library.
Only form iterators that belong to the string and are in a valid order. Adding an index beyond the string’s size, or forming a range whose endpoint precedes its beginning, can cause undefined behavior. If the range is calculated from user input, check the indexes against text.size() before adding them to begin(). For the whole string, using begin() and end() is both simpler and safer.
A string can also be searched through constant iterators when it should not be modified. For example, std::count(text.cbegin(), text.cend(), 'e') expresses a read-only range. The ordinary begin() and end() calls are also fine here because std::count does not write through its iterators.
Counting a Substring Instead
A frequent point of confusion is whether std::count can count a word or substring such as "ana". It cannot do that directly: its third argument is compared with one element at a time, and for a string those elements are individual char values. Searching for a multi-character sequence requires a different approach.
For non-overlapping matches, repeatedly use find and resume after each match. This example counts how many complete, non-overlapping copies of "ana" appear:
std::string text = "banana";
std::string needle = "ana";
std::size_t count = 0;
std::size_t position = 0;
while ((position = text.find(needle, position)) != std::string::npos) {
++count;
position += needle.size();
}
// count is 1
In "banana", the substring begins at index 1. Advancing by the needle’s length means the search resumes after that match, so overlapping matches are not counted. If the intended rule is to count overlapping occurrences, advance by one position instead. Under that rule, "ana" occurs twice in "banana", beginning at indexes 1 and 3. Decide which meaning you need before choosing the loop; neither convention is universally correct.
For a single character, prefer std::count over a manual find loop. It states the intent clearly and handles the full range without custom index bookkeeping.
Case Sensitivity and Text Encoding
std::count compares values exactly. Counting 'A' does not count 'a', and the standard algorithm does not automatically apply language-aware case folding. For plain ASCII text where a case-insensitive count is sufficient, one option is to make a normalized copy and then count the normalized character. Another is to use std::count_if with a predicate that compares normalized characters.
When using the C character-conversion function std::tolower, convert a possibly signed char to unsigned char first. Passing a negative plain-char value (other than EOF) to the C character classification and conversion functions is not valid. Also, the basic std::tolower approach is not a complete solution for Unicode case folding; its behavior depends on the active C locale and it handles single-byte values, not arbitrary Unicode text rules.
There is a related encoding limitation: std::string stores char elements, which are bytes on common implementations. If the string contains UTF-8, a visible character may use several bytes. Counting a byte value with std::count counts matching bytes, not necessarily user-perceived characters. Unicode characters can also be represented by combining sequences, where one displayed symbol consists of multiple code points. For multilingual text, choose a Unicode-aware library and define whether the desired unit is a byte, code point, or grapheme cluster.
Alternatives: count_if and C++20 Ranges
Use std::count_if when the condition is more complex than equality with one character. It accepts a predicate, such as a lambda, and counts each element for which that predicate returns true. For example, this counts decimal digit characters in a string:
std::string text = "room 204";
auto digits = std::count_if(text.begin(), text.end(), [](unsigned char ch) {
return ch >= '0' && ch <= '9';
});
// digits is 3
This explicit comparison is appropriate for the ASCII digits from 0 to 9. For broader character classification, use the right locale-aware or Unicode-aware facility for the text being processed rather than assuming every writing system uses the same byte representation.
C++20 also provides std::ranges::count, which can make the range-first style convenient when ranges are already being used. Include <algorithm> and call it as std::ranges::count(text, 'a'). It performs the same kind of equality count over the range. The traditional std::count(text.begin(), text.end(), 'a') remains widely used and works in older C++ standards, so it is a good choice when supporting projects that do not use C++20.
Performance and Common Mistakes
Counting across a string takes linear time: the algorithm examines every character in the supplied range, so a full-string count performs a number of comparisons proportional to the string’s length. This is the expected cost when the exact total is needed, because any character could be a match. The extra storage used by std::count is constant; it does not need to create a second string or a collection of matches.
- Using double quotes for a character:
'a'is a character;"a"is a string literal. Use the former for the third argument when counting one character. - Expecting a substring count:
std::countcounts individual elements. Usefindin a loop for multi-character sequences. - Ignoring case: matching is exact unless you explicitly normalize or define a case-insensitive predicate.
- Misreading the range endpoint: the last iterator is not included. A range from
begin()toend()nevertheless covers every character. - Assuming a displayed symbol is one char: that assumption can fail for UTF-8 and other multibyte text encodings.
If counts for many different characters are needed, running std::count once for every possible character scans the string repeatedly. That may be perfectly adequate for short strings or a small number of queries. For a larger workload, build a frequency table in one pass, with a data structure and character type chosen for the input encoding. The best option depends on the alphabet and whether the program needs byte counts, code-point counts, or more advanced text handling.
Frequently Asked Questions
Which header is needed for std::count?
Include <algorithm>. A complete program using std::string will usually also include <string>.
Does std::count modify the string?
No. It reads the elements in the supplied range and returns a count; it does not change or erase characters.
How do I count spaces in a C++ string?
Use std::count(text.begin(), text.end(), ' '). The third argument is a single space character enclosed in single quotes.
Can std::count count a word such as “the”?
Not directly. It compares individual string elements, so use repeated find calls or another substring-search approach, and decide whether overlapping matches should count.
Is std::count case-sensitive?
Yes. Uppercase and lowercase letters are different values. Apply an appropriate normalization or comparison rule if the task requires case-insensitive matching.
What does std::count return if there are no matches?
It returns zero. The return type is the iterator range’s difference type, so using auto is a straightforward way to retain the correct type.
Related
- JavaScript String Operations: Methods and Examples
- SQL Split Part: Extract a Value by Position
- What Is a String in JavaScript? Types, Uses, and Examples
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Shortcut to Select the Active Cell’s Entire ColumnIn Excel for Microsoft 365 on Windows, press Ctrl+Space to select the entire worksheet column containing the active…
- Excel Time Format for Milliseconds: Display and CalculateTo show milliseconds in Excel, select the time cells, press Ctrl+1, choose Number > Custom, and enter hh:mm:ss.000…
- Using MAX in Excel: Find the Highest ValueTo find the largest number in Excel, enter =MAX(B2:B10), replacing B2:B10 with the cells you want to check.…
- Google Sheets Filter Wildcards: What Works and HowGoogle Sheets’ basic filter conditions do not treat * or ? as wildcard characters: “Text contains” searches for…
- How to Show a Dropdown List in ExcelTo show a dropdown list in Excel for Microsoft 365 on Windows, select the cell or cells, go…
- Find an Excel Password in a Protected File? Safe OptionsYou usually cannot find or reveal a password from inside a protected Excel file: Excel does not display…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.