The direct answer: C++ does not have a single built-in function named count for strings, but the standard std::string class provides size() (and its alias length()) to count characters, and the <algorithm> header offers std::count to count occurrences of a specific character or substring pattern. For most needs, str.size() is what you want.
Background: Why “count” is ambiguous in C++
Unlike some languages that have a single count() method on strings, C++ separates two distinct ideas:
- Total length – how many characters are in the string. This is handled by
std::string::size()orstd::string::length()(both returnsize_tand are identical in behavior). - Frequency of a specific character or pattern – how many times a given character appears. This is handled by the free function
std::countfrom<algorithm>, or bystd::count_ifwith a predicate.
This separation exists because C++ strings are containers of characters, and the standard library reuses the same algorithms for vectors, lists, and other containers. So std::count works on any container, not just strings.
How to get the string length (the most common “count”)
To count the number of characters in a std::string, call size() or length(). Both are equivalent; length() is inherited from the older C-style string mindset, while size() matches other STL containers.
Example:
#include <iostream>
#include <string>
int main() {
std::string s = "Hello, world!";
std::cout << s.size() << "\n"; // prints 13
std::cout << s.length() << "\n"; // also prints 13
return 0;
}
Note that size() counts bytes, not “characters” in a Unicode sense. For a string containing multi-byte UTF-8 sequences (e.g., “café” with é as two bytes), size() returns the byte count, not the number of visible glyphs. If you need to count Unicode code points or graphemes, you need a library like ICU or a manual UTF-8 decoder.
Counting occurrences of a specific character
To count how many times a particular character appears in a string, use std::count from <algorithm>. It takes a begin iterator, an end iterator, and a value to match.
Example:
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string s = "Mississippi";
int count_s = std::count(s.begin(), s.end(), 's');
std::cout << count_s << "\n"; // prints 4
return 0;
}
For counting characters that satisfy a condition (e.g., digits or uppercase letters), use std::count_if with a lambda:
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string s = "abc123DEF";
int digits = std::count_if(s.begin(), s.end(),
[](unsigned char c){ return std::isdigit(c); });
std::cout << digits << "\n"; // prints 3
return 0;
}
Remember to cast the character to unsigned char when using std::isdigit or similar functions to avoid undefined behavior for negative char values (which can happen with non-ASCII characters on some platforms).
Counting occurrences of a substring
There is no direct std::count for substrings. To count how many times a substring appears, you can use std::string::find in a loop, or use std::search with a counter. The simplest approach is a manual loop:
#include <iostream>
#include <string>
int count_substring(const std::string& haystack, const std::string& needle) {
if (needle.empty()) return 0;
int count = 0;
size_t pos = 0;
while ((pos = haystack.find(needle, pos)) != std::string::npos) {
++count;
pos += needle.size(); // move past this match to avoid overlapping
}
return count;
}
int main() {
std::string s = "abababa";
std::cout << count_substring(s, "aba") << "\n"; // prints 2 (non-overlapping)
return 0;
}
If you want overlapping matches (e.g., “aaa” in “aaaa” should count 2), change pos += needle.size() to pos += 1.
Common pitfalls and misconceptions
- Confusing
size()with capacity:size()is the number of characters currently in the string;capacity()is the allocated memory size, which may be larger. - Counting null characters: A
std::stringcan contain embedded null bytes ('\0').size()counts them correctly, unlike C-strings which stop at the first null. - Using
strlenon astd::string:strlenexpects a C-string and will not work correctly if the string contains nulls, and it requires ac_str()call. Prefersize(). - Forgetting to include
<algorithm>:std::countis not available without it. - Assuming
countis a member function: It is not; it is a free function in thestdnamespace.
Performance and efficiency considerations
Calling size() is O(1) – it simply returns a stored value. Counting occurrences with std::count is O(n), where n is the string length. Substring counting with the loop above is O(n * m) in the worst case (where m is the substring length), but for typical cases it is fine. If you need to count many different characters in a single pass, you can iterate once and fill an array of frequencies:
#include <iostream>
#include <string>
#include <array>
int main() {
std::string s = "hello world";
std::array<int, 256> freq{}; // for char values 0-255
for (unsigned char c : s) {
++freq[c];
}
std::cout << freq['l'] << "\n"; // prints 3
return 0;
}
This is O(n) regardless of how many characters you query later.
Alternatives and related functions
std::string::find– returns the position of the first occurrence of a substring or character, orstd::string::nposif not found.std::string::find_first_of/find_last_of– find positions of any of a set of characters.std::count_if– count elements matching a predicate (e.g., all vowels).- For C-style strings (
char*), usestrlenfor length, but beware of null termination. - For counting words or lines, you would typically split the string or use a stream with
std::istringstream.
Frequently Asked Questions
Is size() the same as length()?
Yes, they are identical. Both return the number of bytes in the string. The standard says they are equivalent, and most implementations just call the same internal function.
How do I count the number of spaces in a string?
Use std::count(s.begin(), s.end(), ' ') with #include <algorithm>. Or loop manually and increment a counter when you see a space.
Does size() count Unicode characters correctly?
No. It counts bytes. For UTF-8 strings, a character like ‘é’ may take 2 bytes, so size() returns 2 for a one-character string. To count Unicode code points, you need a UTF-8 decoder or a library like ICU.
Can I use std::count to count occurrences of a substring?
No, std::count compares whole elements (characters) to a given value. For substrings, you need a loop with find or a more advanced algorithm like std::search with a counter.
Why does size() return size_t and not int?
Because size_t is an unsigned type that can hold the maximum possible size of any object on the platform. Using int could overflow for very long strings. Always use size_t or auto when storing the result.
How do I count characters that are not a specific value?
Use std::count_if with a lambda that returns true for characters you want to count. For example, to count everything that is not ‘a’, use [](char c){ return c != 'a'; }.
Related
- Windows Shortcut Keys: The Complete List
- Shortcut for Minimize? Windows & Mac Keys
- Generate 9 Random Numbers: How to Do It
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- PV vs NPV in Excel: Which Function Should You Use?Use Excel’s PV function to find the present value of regular payments or a future balance; use NPV…
- XLOOKUP to Compare Two Sheets in Excel Step by StepIf Sheet1 has IDs in A2:A100 and Sheet2 has IDs in A2:A100, enter this in Sheet1 cell B2…
- Excel Table Filter Out Duplicates: Keep One Copy SafelyYes—but Excel’s regular table filter does not have a built-in “show only unique rows” switch. To keep one…
- Excel SUMIFS Exclude Multiple Criteria: How-ToThe direct answer: to exclude multiple criteria in Excel’s SUMIFS, you use the “not equal to” operator (<>)…
- VLOOKUP Multiple Values: How to Return All MatchesTo look up several values with VLOOKUP, you cannot use the standard function alone because it returns only…
- How to Convert English to Hindi in Excel with FormulasTo convert English text in Excel to Hindi, enter the text in a cell and use Microsoft 365’s…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.