C++ String Member Functions: A Guide to std::string

Formulas & functions · Updated November 22, 2026

C++ string member functions are operations provided by std::string for examining, searching, changing, and accessing text. The most-used include size(), empty(), find(), substr(), append(), insert(), erase(), and replace(); they belong to the standard library’s string type, not to C-style character arrays.

What std::string represents

The type std::string is an alias for std::basic_string<char>, a standard-library class template that manages a sequence of characters. Include <string> to use it. Unlike a fixed-size C array, a string object tracks its length and can grow or shrink as its contents change. It can also contain a null character inside the sequence; its logical length is not necessarily the same as the length reported by a C function such as strlen.

A minimal example looks like this:

#include <iostream>
#include <string>

int main() {
    std::string name = "Ada";
    name += " Lovelace";
    std::cout << name << ':' << name.size() << '\n';
}

Here, += appends text and size() reports the number of characters in the string. The standard library also provides std::wstring and other character-width variants through basic_string, but ordinary narrow-text examples usually use std::string.

Checking size and accessing characters

size() and length() are equivalent member functions: both return the number of stored char elements as std::string::size_type. That type is unsigned, so avoid comparing it directly with a negative integer. Use empty() when the question is simply whether the string has no characters. max_size() reports a theoretical implementation limit; it does not promise that much memory is available.

Use operator[] or at() to access a character by index. The first does not perform ordinary bounds checking, while at() throws std::out_of_range if the requested position is outside the string. The valid character indices run from zero through size() - 1. front() and back() access the first and last characters, respectively, and should only be used when the string is nonempty.

std::string word = "tree";
char first = word.front();       // 't'
char third = word.at(2);         // 'e'
word[0] = 'T';                   // word is now "Tree"

Indexing and length count char elements, not necessarily user-perceived letters. In UTF-8 text, one visible character can occupy several bytes, so incrementing an index by one may move into the middle of an encoded character.

Finding text and comparing strings

find() searches forward for a character or substring and returns the starting position of the first match. If no match exists, it returns the special value std::string::npos. Because npos is an unsigned sentinel value, compare against it directly rather than treating a search result as a signed integer.

std::string message = "read the manual";
auto position = message.find("manual");
if (position != std::string::npos) {
    std::cout << "Found at " << position << '\n';
}

Related search members include rfind() for searching backward, find_first_of() and find_last_of() for finding any character from a supplied set, and find_first_not_of() and find_last_not_of() for finding a character outside that set. Despite their names, the “of” functions search for any member of the supplied character set, not the entire set as a substring.

compare() performs a lexicographical comparison and returns a value less than, equal to, or greater than zero depending on the ordering. Do not assume it returns exactly -1 or 1. For simple equality or ordering tests, operators such as == and < are often clearer. These comparisons are case-sensitive; std::string has no built-in case-insensitive comparison member.

Changing string contents

There are several ways to add characters or text. append() adds a sequence at the end, push_back() adds one character, and operator+= is a convenient spelling for appending. These operations modify the existing string object and typically return a reference to it, making chained operations possible.

insert() adds characters at a specified position, erase() removes a range, and replace() substitutes a range with new content. Their overloads let you provide a string, a pointer and count, or character data in other supported forms. Check the relevant overload when passing a pointer: a pointer-based overload may expect a null-terminated sequence, while another takes an explicit character count.

std::string label = "blue car";
label.insert(5, "electric "); // "blue electric car"
label.erase(5, 9);            // "blue car"
label.replace(0, 4, "red");   // "red car"
label.push_back('!');

The second argument to erase(position, count) is a count of characters, not an ending index. A position beyond the string’s size can cause std::out_of_range for position-based operations. When modifying a string using positions calculated earlier, remember that insertions and erasures can shift the later positions.

Substrings, clearing, and resizing

substr(position, count) creates and returns a new string containing up to count characters from the requested position. Its default count is std::string::npos, which means to take the remainder. A position greater than the string’s size throws std::out_of_range; a count extending past the end is simply limited to the available characters.

clear() removes all characters, and resize() changes the string’s length. If resizing makes the string longer, the new characters are filled with a specified character, or with null characters if no fill character is provided. pop_back() removes the final character and, like back(), requires a nonempty string.

std::string path = "docs/guide.html";
std::string file = path.substr(5); // "guide.html"
path.resize(4);                    // "docs"
path.clear();                      // empty string

Because substr() returns a new string, it creates a separate value rather than a view into the original. If avoiding a substring copy matters, consider whether a std::string_view is appropriate, while ensuring the original character storage remains alive and unchanged for as long as the view is used.

Capacity, memory, and pointers

capacity() reports how many characters the string can hold in its current allocation before it must grow. It is generally at least as large as size(), but its exact value and growth strategy are implementation details. reserve(n) can request capacity for at least a particular size, which may reduce repeated reallocations when the approximate final length is known. It does not set the string’s length; use resize() to change the number of characters.

shrink_to_fit() is a non-binding request to reduce capacity, so code must not rely on it releasing memory. data() and c_str() provide access to the underlying character sequence, with c_str() returning a null-terminated pointer. Since C++11, the sequence exposed by data() is also null-terminated; since C++17, its returned pointer can be used to modify characters within the string’s current size. Neither pointer grants permission to write beyond that size.

Operations that change a string can invalidate pointers, references, or iterators into its contents, particularly if the operation reallocates storage. Treat such handles as potentially invalid after a modifying operation unless the specific operation’s guarantees say otherwise. Copy the needed character data or reacquire a pointer after mutation when you need a robust approach.

Conversions and related non-member functions

Not every useful string operation is a member function. For example, std::to_string() converts certain numeric values to a string, while functions such as std::stoi() and std::stod() parse numbers from strings. They are standard-library functions, not members called on a string object. Include the appropriate standard headers, commonly <string>, and check parsing behavior: conversion functions can throw exceptions for invalid input or values outside the supported range.

For example, std::stoi("42") produces the integer 42. By default, these conversions may accept a valid numeric prefix and leave trailing characters unconsumed. When validating an entire input, use the overload’s position output parameter and check that the whole string was consumed, or choose a parsing approach that matches the input rules. For locale-independent, non-allocating parsing of character ranges, C++17 also provides the separate std::from_chars facility for supported numeric types.

There are also non-member utilities and operators. The + operator can join strings and character sequences into a result, while std::getline() reads a line into a string. The distinction matters when looking up documentation: search for a member when the operation is called on an object, and for a standard function or operator when it is not.

Choosing the right member and avoiding mistakes

Choose a function based on the operation and the guarantees you need, not just on the shortest syntax. A useful quick guide is:

  • Use empty() for an emptiness test and size() when you need the character count.
  • Use at() when checked indexing is useful; use [] when the index is already known to be valid.
  • Use find() and compare with npos to test for a substring.
  • Use append(), +=, or push_back() for adding content; use replace() when changing a range.
  • Use substr() for a standalone copy of part of a string, not as a zero-copy view.

A frequent misconception is that std::string is a C string. It is not: it stores a length and can include embedded null characters. Passing c_str() to a C API is useful when the API expects a null-terminated string, but that API will normally treat the first null character as the end. Also, a string’s member functions do not automatically interpret Unicode grapheme clusters or perform case folding. For international text processing, character encoding and a suitable Unicode library may be necessary.

Another common error is writing if (text.find(query)). A match at index zero converts to false, and npos is not the right condition either. Write text.find(query) != std::string::npos to express the intended test explicitly.

Frequently Asked Questions

What are the most common std::string member functions?
Common choices are size(), empty(), at(), find(), substr(), append(), insert(), erase(), replace(), and clear(). The right set depends on whether you are inspecting, searching, or changing text.

What is the difference between size() and length()?
For std::string, there is no difference in result: both return the number of stored characters. They are interchangeable, though size() is common when working with standard containers generally.

Does find() return -1 when it cannot find text?
No. It returns std::string::npos, a special unsigned value. Compare the result with that constant instead of checking for -1.

Is substr() a member function and does it change the original?
substr() is a member function, but it returns a new string and leaves the original unchanged. Its position must not be greater than the original string’s size.

How do I get a C-style string from std::string?
Call c_str() to obtain a pointer to null-terminated character data. The pointer is associated with the string’s storage, so do not keep relying on it after an operation that may modify or reallocate the string.

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.