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 copying1bool startsWith(string_view str, string_view prefix) { // Compares the first prefix.size() characters with prefix2 return str.substr(0, prefix.size()) == prefix;3}4 // Returns the n-th word as a view into str5string_view extractWord(string_view str, size_t n) { // start: where the current word begins; count: its index6 size_t start = 0, count = 0; // <= so the end of the string also closes the last word7 for (size_t i = 0; i <= str.size(); i++) { // A word ends at a space or at the end8 if (i == str.size() || str[i] == ' ') { // If it is the wanted word, return that slice9 if (count == n) return str.substr(start, i - start); // Otherwise move on to the next word10 count++;11 start = i + 1;12 }13 } // Not enough words: an empty view14 return {};15}16 // text must outlive the views returned into it17string 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. 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