10 Examples of using string_view in C++
And 2 more code examples ready as implementation.
std::string_view is a class named
basic_string_view that uses
std::char_traits , both as a template.
It is only available from C++17 and needs to include the
string_view header. Can be implemented also for accented letters(
std::wstring_view), unicode 8(
std::u16string_view, C++20) and 32(
std::u32string_view ) .
It pretty much creates an array of characters for a string.
Each character is an index:
It is widely used in code that parses.
Let’s see 10 examples of using it!
01. Basic usage, declaring, initializing and printing a
02. Print only the 4th (fourth character)
03. Get the size of the
#04. Print the last character
05. Know the position of the character
#06. Knowing the back to front position
It would be the 1st ‘o’ backwards, the
find()would be 10 . Another note is if you enter a character that doesn’t exist, it will give garbage(
string::npos, a weird number).
07. Check for
08. Print 9th to 13th character
09. Remove the last 4 characters
#10. Remove the first 8 characters
You can also use
string_view_literals by adding the term
sv to the end, example code with literal:
Example of a ready code:
Some other functions are only available in C++20 or C++23, examples:
starts_with() and others.
For more information visit: https://en.cppreference.com/w/cpp/string/basic_string_view .