Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::string_view — a non-owning view of text

std::string_view provides access to text without copying characters or owning their storage. Learn to search with find, create subviews with substr, and check npos while keeping the underlying data alive.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <string_view>
std::string_view view = "key=value";
auto pos = view.find('=');
if (pos != std::string_view::npos) {
    auto part = view.substr(pos + 1);
}

std::string_view, from <string_view>, is an alias for std::basic_string_view<char>. It describes contiguous characters using a pointer and a length. It does not own the data; copying a view does not copy characters. It prevents character modification through the view but does not freeze the underlying storage.

std::string_view::find searches for a character or substring starting at pos (default 0). It returns the first matching index, measured from the beginning of the view, or std::string_view::npos. This constant has the value size_type(-1) and signals no match. Check it before calculating pos + 1 or using the result as an index; do not treat the result as a Boolean, because index 0 is valid.

std::string_view::substr(pos, n) returns another view without copying characters, in constant time. Its length is the smaller of n and size() - pos; the default n = npos means the remainder. For pos == size(), the result is empty; for pos > size(), it throws std::out_of_range.

The data must remain valid while the view or its subviews are used. A view does not extend their lifetime: destroying the source std::string or reallocating its buffer can leave a dangling view. data() does not guarantee a terminating \0; do not pass it directly to a function requiring a null-terminated string.

The example splits text into a key and value. The literal has static storage duration, so both subviews remain valid. Entry scope: C++23; the repository compiler flag does not attest the production runtime. The source is an evolving working draft, not a frozen C++23 publication.

Examples

#include <iostream>
#include <string_view>

int main() {
    constexpr std::string_view text = "name=Ada";
    constexpr auto pos = text.find('=');
    static_assert(pos != std::string_view::npos);
    constexpr auto key = text.substr(0, pos);
    constexpr auto value = text.substr(pos + 1);
    static_assert(key == "name" && value == "Ada");

    std::cout << key << '\n' << value << '\n';
}

Result

name
Ada

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources