Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Containers

C++ std::string class

Reference for std::string: construction, element access, size and capacity, modification, searching, comparison, small string optimization and common pitfalls.

std::string (header <string>) is the standard owning text type: a contiguous, resizable sequence of char that manages its own memory. It is an alias for std::basic_string<char>; the same template gives std::wstring, std::u8string, std::u16string and std::u32string. Strings are regular value types: copying one copies the characters, and the memory is released automatically when the object is destroyed.

A string always keeps a terminating null character after its last element, so c_str() and data() can hand the buffer to C APIs. It can also contain embedded '\0' characters, because its length is stored separately. Short strings usually live inside the object itself (the small string optimization) and need no heap allocation.

C++
#include <string>

std::string s = "hello";
s += ", world";

Try it

C++ Building and inspecting a string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ Embedded nulls and exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
std::string();
std::string(const char* s);
std::string(const char* s, std::size_t count);
std::string(std::size_t count, char ch);
std::string(const std::string& other);
std::string(std::string&& other) noexcept;
std::string(std::initializer_list<char> init);
Name Description
s Null-terminated C string to copy. Passing a null pointer is undefined behavior (C++23 deletes the nullptr_t overload so std::string(nullptr) fails to compile).
count Number of characters to copy, or to repeat for the fill constructor.
ch Character used by the fill constructor and by resize.

Main member groups:

Group Members
Access operator[], at, front, back, data, c_str
Size size, length, empty, capacity, reserve, shrink_to_fit, max_size
Modify append, operator+=, push_back, pop_back, insert, erase, replace, resize, clear, assign, swap
Search find, rfind, find_first_of, find_last_of, find_first_not_of, find_last_not_of, contains (C++23), starts_with, ends_with (C++20)
Other substr, compare, copy, begin/end and the reverse iterators

Returns: search functions return an index, or std::string::npos (the largest size_t value) when nothing matches. substr returns a new string.

Errors / undefined behavior: at(), substr() with a start past the end, and insert/erase/replace with a bad position throw std::out_of_range. operator[] is not checked; reading s[size()] yields '\0' but any other out-of-range index is undefined. Growing past max_size() throws std::length_error.

Usage notes

  • Search results are unsigned. Compare with std::string::npos, never with -1 stored in an int.
  • Iterators, pointers and references are invalidated by any operation that reallocates (growth past capacity()), and by erase/insert at or before their position. See iterator invalidation.
  • Cost: size() and indexing are O(1); push_back is amortized O(1); insert and erase in the middle are O(n); find is O(nยทm) in the worst case; + creates a new string, so build long text with +=, append or a std::string that called reserve.
  • Small string optimization: libstdc++ stores up to 15 characters inline; other libraries use a different limit. Do not rely on a particular number, and never assume the buffer address stays the same after a move.
  • Parameters: take std::string_view for read-only text and const std::string& only when you need the terminator. See std::string_view.
  • Literals: "text"s (from std::literals) creates a std::string without a const char* detour. Concatenating two plain literals with + does not compile.
  • c_str() and data() pointers are valid until the string is modified or destroyed. Since C++17 data() also has a non-const overload.
  • Unicode: a std::string stores bytes. size() counts char units, not characters, so UTF-8 text such as "รฉ" has size 2.
  • Comparison with ==, < and <=> is lexicographic by char value; it is not locale-aware (use std::collate for that).
  • Conversions between numbers and text: std::to_string, std::stoi, std::from_chars (see string conversions).