std::string_view is a class named basic_string_view that uses char and 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::u8string_view), 16(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:
T
e
r
m
i
n
a
l
R
o
o
t
0
1
2
3
4
5
6
7
8
9
10
11
12
It is widely used in code that parses.
Let’s see 10 examples of using it!
01. Basic usage, declaring, initializing and printing a string_view
02. Print only the 4th (fourth character)
03. Get the size of the string_view
#04. Print the last character
05. Know the position of the character 'i'
#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 'X' character
08. Print 9th to 13th character
09. Remove the last 4 characters
#10. Remove the first 8 characters
bonus
You can also use string_view_literals by adding the term sv to the end, example code with literal:
Example of a ready code:
Saída:
Some other functions are only available in C++20 or C++23, examples: contains(), starts_with() and others.