String Functions in C++ STL: Full List

Formulas & functions · Updated November 22, 2026

The C++ Standard Template Library (STL) provides a rich set of string functions through the std::string class, covering construction, modification, inspection, searching, and conversion. These functions are part of the <string> header and operate on dynamic character arrays, offering safe and convenient alternatives to C-style strings.

Background: From C Strings to std::string

Before the STL, C programmers used null-terminated character arrays (char[]) with functions like strlen(), strcpy(), and strcat(). These were error-prone: you had to manually manage memory, avoid buffer overflows, and remember to include the terminating null character. std::string was introduced in the C++ standard library to encapsulate these operations, automatically managing memory and providing a consistent interface. It first appeared in the 1998 C++ standard and has been extended since (e.g., C++11 added shrink_to_fit(), C++17 added data() returning non-const pointer, C++20 added starts_with() and ends_with()). The class is defined in the <string> header, and it is actually a typedef for std::basic_string<char>, which can be instantiated for other character types like wchar_t (wide strings) or char8_t (UTF-8).

Core Functions: Construction and Assignment

You can create strings in several ways, and assign or append to them using operators or member functions.

  • Constructors: std::string s; (empty), std::string s("hello"); (from C-string), std::string s(10, 'x'); (10 copies of ‘x’), std::string s(other); (copy constructor).
  • Assignment: s = "new"; or s.assign("new"); – both replace the current content.
  • Appending: s += " world"; or s.append(" world"); – adds to the end. There is also push_back(char) to add a single character.
  • Insertion: s.insert(pos, str); inserts a string at a given index (0-based).
  • Erasing: s.erase(pos, len); removes len characters starting at pos.
  • Clearing: s.clear(); removes all characters, leaving an empty string (size 0).

Example: std::string s = "Hello"; s += " World"; results in "Hello World".

Inspection and Access: Size, Length, and Characters

To read or check the contents of a string, you have several functions:

  • size() and length() – both return the number of characters (they are synonyms). Use empty() to check if size is zero.
  • operator[] and at() – access a character at a given index. at() performs bounds checking and throws std::out_of_range if the index is invalid, while operator[] does not (undefined behavior if out of bounds).
  • front() and back() – return the first and last character, respectively (C++11 onward).
  • c_str() and data() – return a pointer to a null-terminated character array. data() since C++11 also guarantees null-termination; before that it was not guaranteed.
  • substr(pos, len) – returns a new string that is a substring starting at pos of length len. If len is omitted, it takes the rest of the string.

Search and Comparison Functions

Finding characters or substrings is a common task. The main search functions are:

  • find(str, pos) – returns the index of the first occurrence of str starting from pos (default 0). Returns std::string::npos if not found.
  • rfind(str, pos) – searches backward from pos (default end) for the last occurrence.
  • find_first_of(str, pos) – finds the first character that matches any character in str.
  • find_last_of(str, pos) – finds the last character that matches any character in str.
  • find_first_not_of(str, pos) – finds the first character that is not in str.
  • find_last_not_of(str, pos) – finds the last character that is not in str.
  • compare(str) – compares lexicographically; returns 0 if equal, negative if less, positive if greater. You can also use operators ==, !=, <, etc., which are more readable.

Example: std::string s = "Hello World"; size_t pos = s.find("World"); yields pos == 6. If not found, pos == std::string::npos (which is static_cast<size_t>(-1)).

Modification and Conversion Functions

Beyond basic editing, there are functions to change the string’s contents or convert to other types.

  • replace(pos, len, str) – replaces a substring with str.
  • swap(other) – exchanges contents with another string efficiently (constant time).
  • resize(n) – changes the length; if shorter, characters are truncated; if longer, new characters are default-initialized (or you can specify a fill character).
  • reserve(n) – pre-allocates memory for at least n characters to avoid reallocations during repeated appends.
  • shrink_to_fit() – requests the capacity to be reduced to fit the size (non-binding, implementation may ignore).
  • Numeric conversions (C++11): stoi(), stol(), stoll(), stof(), stod(), etc., convert a string to integer or floating-point types. Example: int n = std::stoi("42");
  • To convert numbers to string, use std::to_string() (C++11). Example: std::string s = std::to_string(3.14); yields "3.140000".
  • Character classification: std::isalpha(), std::isdigit(), etc., are in <cctype> and work on individual characters, not directly on strings.

Common Problems and How to Avoid Them

Even with std::string, there are pitfalls:

  • Using npos incorrectly: Always check if (s.find(...) != std::string::npos) before using the index. Forgetting this leads to using a huge number as an index.
  • Out-of-bounds access: Prefer at() over operator[] when you are not sure the index is valid, to catch errors with exceptions.
  • Modifying while iterating: If you call functions like insert() or erase() inside a loop that uses indices, the indices shift. Use iterators carefully or recompute indices.
  • Performance with many concatenations: Repeated += can cause multiple reallocations. Use reserve() beforehand or use std::ostringstream for complex formatting.
  • Confusing size() with capacity(): size() is the number of characters, capacity() is the allocated memory size. They differ after reserve().
  • Null characters in strings: std::string can contain embedded null characters, but c_str() returns a C-string that stops at the first null. Use data() and size() together for binary data.

Alternatives and Related Facilities

While std::string is the primary class, there are alternatives depending on the need:

  • std::string_view (C++17): A non-owning view of a string. Use it for function parameters to avoid copying when you only need to read the string. It does not allocate memory and cannot modify the underlying data.
  • Character arrays (char[]): Still used for low-level or performance-critical code, but you must manage memory manually.
  • std::wstring: For wide characters (e.g., Unicode on Windows). Similar functions but with wchar_t.
  • Regular expressions (std::regex): For pattern matching, not just simple search. More powerful but slower.
  • std::ostringstream: For formatted output (like printf but type-safe). Good for building strings with mixed types.

Frequently Asked Questions

What is the difference between size() and length()?

There is no difference. Both return the number of characters in the string. length() is kept for compatibility with C-style string functions, while size() is consistent with other STL containers like std::vector.

How do I convert a string to an integer?

Use std::stoi() (string to int). For example: int x = std::stoi("123"); It throws std::invalid_argument if no conversion could be performed, and std::out_of_range if the value is out of range. For long or long long, use stol() or stoll().

Why does find() return npos and how do I check it?

npos is a special constant (usually the maximum value of size_t) that indicates “not found”. Always compare the return value with std::string::npos to check if a substring exists. For example: if (s.find("needle") != std::string::npos) { /* found */ }.

Can I use std::string with binary data?

Yes, because std::string can hold null characters. Use the constructor that takes a pointer and length: std::string s(data, len). When accessing the data, use data() and size() instead of c_str() (which truncates at the first null).

How do I split a string by a delimiter?

There is no built-in split() function in the STL. A common approach is to use find() and substr() in a loop. For example, to split on commas:

std::vector<std::string> parts;
size_t start = 0, end = 0;
while ((end = s.find(',', start)) != std::string::npos) {
    parts.push_back(s.substr(start, end - start));
    start = end + 1;
}
parts.push_back(s.substr(start));

Alternatively, use std::getline() with a string stream for line-based splitting.

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.