String View in C++

Level 5524 keystrokes

string_view refers to existing characters without copying them, so substr() on it is cheap. startsWith compares a prefix, and extractWord returns the n-th space-separated word (counting from 0) as a view into the original text.

C++ code

// Both string and string literals convert to string_view without copying
1bool startsWith(string_view str, string_view prefix) {
// Compares the first prefix.size() characters with prefix
2 return str.substr(0, prefix.size()) == prefix;
3}
4
// Returns the n-th word as a view into str
5string_view extractWord(string_view str, size_t n) {
// start: where the current word begins; count: its index
6 size_t start = 0, count = 0;
// <= so the end of the string also closes the last word
7 for (size_t i = 0; i <= str.size(); i++) {
// A word ends at a space or at the end
8 if (i == str.size() || str[i] == ' ') {
// If it is the wanted word, return that slice
9 if (count == n) return str.substr(start, i - start);
// Otherwise move on to the next word
10 count++;
11 start = i + 1;
12 }
13 }
// Not enough words: an empty view
14 return {};
15}
16
// text must outlive the views returned into it
17string text = "Hello World from C++";
// true without boolalpha: prints "Starts with 'Hello': 1"
18cout << "Starts with 'Hello': " << startsWith(text, "Hello") << endl;
// Word 0 is Hello, so word 2 is "from"
19cout << "Word 2: " << extractWord(text, 2) << endl;

Output

Starts with 'Hello': 1
Word 2: from
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • =× 14
  • <× 13
  • (× 12
  • )× 12
  • ;× 11
  • "× 8
  • _× 7
  • ,× 7
  • +× 7
  • .× 5

More C++ examples at level 5

← C++ typing practice