string_view in C++
A window into someone else's characters: substrings with no copies, checked at compile time.
#include <string_view>
constexpr std::string_view greeting = "Hello, typestar!";
constexpr std::string_view first_word(std::string_view text) {
return text.substr(0, text.find(' '));
}
static_assert(first_word(greeting) == "Hello,");
static_assert(greeting.substr(7).starts_with("type"));
static_assert(greeting.ends_with('!'));
How it works
std::string_viewpoints at existing characters —greetingowns nothing and copies nothing.substrandfindreturn new views into the same buffer, sofirst_wordnever allocates.- Every operation here is
constexpr, lettingstatic_asserttest the slicing at compile time.
Keywords and builtins used here
constexprfirst_wordreturnstatic_assert
The run, in numbers
- Lines
- 11
- Characters to type
- 331
- Tokens
- 87
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 70 seconds.
Step 1 of 3 in Strings & streams, step 19 of 27 in Language basics.