C++ String Functions: What They Do and How to Use Them

Formulas & functions · Updated November 22, 2026

In C++, string functions are operations such as size(), find(), substr(), and replace() on std::string. If you mean x++, that is not a string function: applying it to a std::string is an error, although ++ can advance a string iterator.

What x++ means in C++

The expression x++ is the postfix increment operator. It is used with a value that supports incrementing, such as an integer: if x is 4, then x++ evaluates to the old value, 4, and leaves x as 5. The expression is not a general-purpose way to change a value, and std::string does not define increment operators.

For example, this is invalid C++:

std::string x = "cat";
x++;

If the intention is to add text, use an operation such as += or append() instead. If the intention is to move through the characters in a string, increment an iterator, not the string itself. An iterator is a separate object that refers to a position in the string.

std::string x = "cat";
x += "s"; // x is now "cats"

That distinction resolves a common confusion: C++ has string operations, but x++ is not one of them.

How std::string works

The standard C++ string type is std::string, declared in the <string> header. It stores a sequence of characters and manages its own memory, so ordinary string use does not require manually allocating a character buffer. Include the header and qualify the type with std::, unless the program has deliberately brought names into scope.

#include <string>

int main() {
    std::string greeting = "Hello";
}

A string literal such as "Hello" can initialize a std::string. The string can then grow or shrink as operations modify it. Its characters are stored in sequence, and their positions are numbered from zero: in "Hello", 'H' is at index 0 and 'e' is at index 1.

In everyday C++ usage, people often say “string functions” to mean both member functions, called with dot notation, and related operators such as + and ==. These are not all technically functions, but together they provide the common ways to inspect, search, compare, and change text.

Checking a string’s size and contents

Use size() or its synonym length() to get the number of stored char elements. For a string containing ordinary English text, this usually matches the visible character count. empty() reports whether the string has no elements, and at() accesses a character with bounds checking.

std::string word = "river";
auto count = word.size();       // 5
auto sameCount = word.length(); // 5
bool blank = word.empty();      // false
char first = word.at(0);        // 'r'

Square brackets also access a character, as in word[0], but unlike at(), they do not perform bounds checking. Accessing an invalid position is a bug and can produce undefined behavior. Use at() when checking the index matters; use [] when the program already guarantees it is valid.

One important limitation is that std::string counts bytes, not necessarily human-perceived characters. UTF-8 text can use multiple bytes for one displayed symbol, so size() may be larger than the number of visible letters or symbols. Basic string operations do not automatically interpret Unicode grapheme boundaries.

Adding, changing, and removing text

For short additions, += is convenient. It accepts another string, a string literal, or a character. The member function append() provides similar behavior and can be useful when its overloads make the intended operation clearer. push_back() adds one character, while clear() removes all characters.

std::string message = "Good";
message += " morning";
message.push_back('!'); // "Good morning!"
message.clear();        // empty string

Use insert() to place text at a position, erase() to remove a range, and replace() to exchange a range for different text. Positions are zero-based. For operations that take a position and a count, the count describes how many characters to affect, not the final index.

std::string label = "blue car";
label.insert(4, " electric"); // "blue electric car"
label.erase(4, 9);             // "blue car"

In this example, the inserted text begins at index 4. The erase call then removes nine characters beginning at that same position, returning the string to its original contents. Be careful when calculating ranges: a position beyond the string’s size can cause an exception for operations that check positions, while a count that extends past the end is generally limited to the available characters.

Finding text and extracting part of it

find() searches for a character or substring and returns the position of its first match. If there is no match, it returns the special value std::string::npos, not an ordinary negative index. A safe search checks for that value before using the result as a position.

std::string sentence = "tea, coffee, tea";
auto position = sentence.find("coffee");
if (position != std::string::npos) {
    // position is 5
}

Related search members include rfind(), which searches from the end, and character-set searches such as find_first_of() and find_first_not_of(). These can help locate delimiters or skip a group of characters. They search for characters from a set; they do not parse a complete grammar or automatically understand words.

substr(position, count) returns a new string containing a portion of the original. The count is optional; when omitted, the result runs from the chosen position to the end. As with other position-based operations, indexes start at zero.

std::string code = "AB-4821";
std::string prefix = code.substr(0, 2); // "AB"
std::string number = code.substr(3);    // "4821"

For more involved text splitting, a loop using find() and substr() can work, but it needs deliberate handling of missing delimiters and empty fields. Newer C++ versions also offer facilities such as std::string_view for non-owning views, and C++23 includes std::ranges::views::split. These are alternatives for particular tasks, not replacements for learning basic string operations.

Comparing strings and converting values

Strings can be compared with operators such as ==, !=, and <. Equality checks whether the sequences match; ordering is lexicographical, based on the character values, rather than a human-language dictionary comparison. For instance, capitalization and the character encoding affect ordering, so a basic comparison is not automatically case-insensitive or locale-aware.

The member compare() also compares strings and returns a value less than zero, zero, or greater than zero according to their ordering. In most everyday code, the comparison operators are easier to read. To compare without regard to case, convert or compare characters using an explicitly chosen approach; do not assume that ordinary string equality ignores capitalization.

To convert a number to a string, C++ provides functions such as std::to_string() in <string>. For parsing, functions such as std::stoi() convert text to an integer, but parsing can fail and may throw an exception for invalid or out-of-range input. For more controlled numeric parsing, std::from_chars is available in modern C++ and reports errors through its result rather than using exceptions.

int quantity = 12;
std::string text = "items: " + std::to_string(quantity);

Do not confuse these conversion functions with string members: to_string() is not called as text.to_string(). Nor does a string’s find() or substr() convert text into a number; those operations only search or extract characters.

std::string versus C-style strings

A C-style string is usually a character array or pointer whose text ends with a null character, written '\0'. A std::string manages its length separately and can contain a null character within its stored sequence. The two forms can interoperate, but they are not interchangeable in every operation.

The c_str() member returns a pointer to a null-terminated character sequence representing the string, which is useful when calling an older C library that expects a C-style string. The pointer is tied to the string’s storage; changing the string can invalidate pointers or references to its characters. Do not keep such a pointer for later use across modifications unless the relevant lifetime and invalidation rules are understood.

When a program needs to read a whole line, std::getline() is often more appropriate than formatted extraction with operator>>. Formatted extraction normally stops at whitespace, whereas getline() reads through the line delimiter. If formatted input has just left a newline in the stream, account for it before calling getline(), or the next line read may appear empty.

Common mistakes and practical choices

Most string bugs come from mixing up positions, sizes, and types. A useful rule is to check what each operation returns: size() returns a size type, find() returns a position or npos, and substr() returns a new string. Avoid assuming that an unsuccessful search returns -1 and then using that result as an index.

  • Use std::string for ordinary owned text that may change in length.
  • Use std::string_view when a function only needs to read a character sequence without taking ownership, while ensuring the referenced text remains alive.
  • Use C-style character arrays only when an interface or low-level requirement calls for them; they require careful attention to buffer size and termination.
  • Use dedicated Unicode-aware libraries or facilities when the task requires case folding, normalization, or counting user-perceived characters.

Another common mistake is treating std::string as though it has built-in trim, split, or case-conversion members. The standard string class does not provide members named trim(), split(), or to_lower(). Such tasks can be implemented with algorithms and character-handling functions, or handled by an appropriate library. Choosing a clear, well-tested approach is preferable to guessing at a function name that the standard does not define.

Frequently Asked Questions

Can you use x++ on a C++ string?
No. A std::string does not support the increment operator. Use += or append() to add text, or increment an iterator to move to another character position.

What is the most commonly used C++ string function?
There is no single most-used function, but size(), empty(), find(), substr(), and append() are common. The right choice depends on whether the task is inspection, searching, extraction, or modification.

What does find() return when it cannot find a match?
It returns std::string::npos. Compare the result with that constant before treating it as a valid position.

Are size() and length() different?
No. For std::string, length() is equivalent to size(); both report the number of stored char elements.

Does C++ have a built-in split or trim string function?
std::string has no member named split() or trim(). Splitting can be done with searches or newer range facilities, while trimming generally requires a small algorithm or a library.

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.