String count function in C++? (std::string::size)

Formulas & functions · Updated November 23, 2026

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() or std::string::length() (both return size_t and 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::count from <algorithm>, or by std::count_if with 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::string can contain embedded null bytes ('\0'). size() counts them correctly, unlike C-strings which stop at the first null.
  • Using strlen on a std::string: strlen expects a C-string and will not work correctly if the string contains nulls, and it requires a c_str() call. Prefer size().
  • Forgetting to include <algorithm>: std::count is not available without it.
  • Assuming count is a member function: It is not; it is a free function in the std namespace.

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, or std::string::npos if 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*), use strlen for 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

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.