Skip to content
C++ Basics: Advance a Text View Without Copying

C++ Basics: Advance a Text View Without Copying

November 6, 2026

Use string_view::remove_prefix to consume a recognized label while leaving the original text intact.

Prepare a scratch directory

Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.

Keep the same terminal open. Stop if setup fails, before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save this as string-view-remove-prefix-parser-demo.cpp:

#include <iostream>
#include <string>
#include <string_view>

int main()
{
    const std::string line = "name=alpha";
    std::string_view remaining = line;
    constexpr std::string_view prefix = "name=";
    if (remaining.starts_with(prefix)) {
        remaining.remove_prefix(prefix.size());
    }
    std::cout << "value: " << remaining << '\n';
    std::cout << "original: " << line << '\n';
    remaining.remove_prefix(remaining.size());
    std::cout << "empty: " << std::boolalpha << remaining.empty() << '\n';
}

Compile and run it. The program runs only after compilation succeeds:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic string-view-remove-prefix-parser-demo.cpp -o string-view-remove-prefix-parser-demo &&
./string-view-remove-prefix-parser-demo

Observed output:

value: alpha
original: name=alpha
empty: true

Read the result

The view first exposes alpha, while the owning string still contains name=alpha. Consuming the remaining size leaves an empty view. Neither operation erases characters from the string.

Apply it carefully

The removal count must not exceed the view size; remove_prefix does not perform a checked erase. The starts_with test establishes that the prefix fits. Keep the owner alive and avoid changes that invalidate its storage. A view does not own its characters and is not necessarily null-terminated.

The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.

Clean up

Remove only the source and executable created here, then return to the starting directory:

rm -- string-view-remove-prefix-parser-demo.cpp string-view-remove-prefix-parser-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect its remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on