C++ Reference ยท Strings and I/O
C++ string::substr
Extract part of a std::string with substr(pos, count): default arguments, out_of_range rules, copies versus string_view slices and common splitting patterns.
substr(pos, count) returns a new std::string holding up to count characters starting at index pos. The count defaults to npos, meaning "to the end". The original string is unchanged, and the result is an independent copy.
Because the result is a copy, substr costs O(count) and may allocate. When you only need to read a slice, std::string_view::substr returns a view without copying, as long as the original string outlives it.
std::string s = "hello world"; s.substr(6); // "world" s.substr(0, 5); // "hello" s.substr(3, 100); // "lo world": count is clamped
Try it
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.
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
basic_string substr(size_type pos = 0, size_type count = npos) const; // C++11 basic_string substr(size_type pos = 0, size_type count = npos) const&; // C++23 basic_string substr(size_type pos = 0, size_type count = npos) &&; // C++23
| Name | Description |
|---|---|
pos |
Index of the first character to copy. Must be <= size(). |
count |
Maximum number of characters; the real length is min(count, size() - pos). |
Returns: a new string containing the selected characters.
Errors: throws std::out_of_range if pos > size(). pos == size() is allowed and returns an empty string.
Usage notes
- Only
posis checked. An oversizedcountis silently reduced, sos.substr(0, 1000)is safe. - It is a copy. Edits to the result do not affect the source. In C++23, calling
substron an rvalue string reuses its buffer, sostd::move(s).substr(n)avoids an extra allocation. - Prefer views for read-only slices.
std::string_view(s).substr(a, b)does not allocate; just keep the string alive and unchanged while you use the view. - Do not build with
s.substr(i, 1)in loops to get single characters: uses[i]ors.at(i). - Negative positions do not exist. Passing
-1converts to a huge unsigned value and throws. Compute from the end withs.size() - nafter checkingn <= s.size(). - Alternatives: the constructor
std::string(s, pos, count)does the same job; the iterator constructorstd::string(s.begin() + a, s.begin() + b)never throws for valid iterators. - Equality helpers:
starts_withandends_with(C++20) replaces.substr(0, n) == prefix.