C/C++ Arena

Step 3 of 6

std::string_view

std::string_view is a lightweight, non-owning view of characters: a pointer plus a length. It accepts string literals, std::strings and substrings without copying anything, which makes it the modern choice for read-only string parameters.

int count_upper(std::string_view s);
count_upper("AWP");            // no std::string is created
s.substr(1, 2);                // also a view, no copy
s.starts_with("de_");          // C++20

Danger: a view doesn't keep the text alive. Never return a view of a local string.

Your turn: write std::string_view trim(std::string_view s) that returns the view without leading and trailing spaces.

Previous: std::variant and std::visit Next: Concepts