typestar

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

  1. std::string_view points at existing characters — greeting owns nothing and copies nothing.
  2. substr and find return new views into the same buffer, so first_word never allocates.
  3. Every operation here is constexpr, letting static_assert test the slicing at compile time.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Strings & streams, step 19 of 27 in Language basics.

← Previous Next →