Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::basic_string::substr — owning substring

Extract part of a string into a new owning string. Learn how the length is capped, when the start position throws, and what the C++23 rvalue overload changes.

Version: ISO C++23; implementation support may vary

Syntax

// ISO C++23 — member declarations in std::basic_string (<string>)
constexpr basic_string substr(size_type pos = 0, size_type count = npos) const &;
constexpr basic_string substr(size_type pos = 0, size_type count = npos) &&;

std::basic_string::substr is a member function declared in <string>. s.substr(pos, count) returns a new owning string of the same type. pos is a zero-based start index; count is an element count, not an end index. pos defaults to 0, and count defaults to npos, meaning “through the end”.

When pos <= s.size(), the result contains std::min(count, s.size() - pos) elements. An oversized count is capped; pos == s.size() or count == 0 with a valid pos yields an empty string. pos > s.size() throws std::out_of_range even if count == 0. Validate negative input before converting it to unsigned size_type, and check the length before computing s.size() - 4 to prevent unsigned wraparound.

Before C++23 there was one const overload, constexpr since C++20. In C++23 both overloads are constexpr; library support may vary. const & copies the selected range without changing the source. && is selected for a non-const rvalue such as std::move(s) and may reuse the source's storage, but no allocation-free guarantee is given. After success the source is valid but in an unspecified state. Both overloads default-construct the result's allocator rather than copying s.get_allocator(). If an exception is thrown, the source is unchanged.

Positions and lengths count CharT elements: bytes for std::string, and char8_t UTF-8 code units for std::u8string. Slicing UTF-8 can split a code point. substr preserves embedded zero elements; to copy the entire range exactly, pass both s.data() and s.size() to the string constructor, not just the pointer. Unlike an owning string, the result of std::basic_string_view::substr borrows its data; use it only while the backing storage remains valid.

For letters and digits from the basic character set, s.substr(0, 3) takes up to the first three letters if they are at the start, and s.substr(3) takes the rest if s.size() >= 3. substr slices; it does not filter. For a string already made up of digits, use digits.substr(digits.size() - 4) if it has at least four elements; otherwise prepend zeros with std::string(4 - digits.size(), '0').

Examples

#include <iostream>
#include <stdexcept>
#include <string>

std::string last_four(const std::string& digits) {
    if (digits.size() < 4) {
        return std::string(4 - digits.size(), '0') + digits;
    }
    return digits.substr(digits.size() - 4);
}

int main() {
    const std::string label = "ABC12345";
    std::cout << label.substr(0, 3) << '\n';
    std::cout << label.substr(3, 99) << '\n';
    std::cout << last_four(label.substr(3)) << '\n';
    std::cout << last_four("7") << '\n';
    std::cout << '[' << label.substr(label.size()) << "]\n";

    try {
        (void)label.substr(label.size() + 1, 0);
    } catch (const std::out_of_range&) {
        std::cout << "out_of_range\n";
    }
}

Result

ABC
12345
2345
0007
[]
out_of_range

The example shows a prefix, a capped count, keeping the last four digits or padding on the left, and the difference between starting at the end and starting past it.

Related lessons

  • C++ · Lesson 49 · Advanced · Version: 3
  • C++ · Lesson 53 · Advanced · Version: 3

Sources