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!
string_view
std::string_view sv {"Terminal Root"};
std::cout << sv << '\n';
std::cout << sv[3] << '\n'; // m
string_view
std::cout << sv.size() << '\n'; // 13
#04. Print the last character
std::cout << sv.back() << '\n'; // t
'i'
std::cout << sv.find("i") << '\n'; // 4
#06. Knowing the back to front position
std::cout << sv.rfind("o") << '\n'; // 11
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).
'X'
characterstd::cout << sv.find("X") << '\n'; // garbage
std::cout << sv.substr(9, 13) << '\n'; // root
sv.remove_suffix(4);
std::cout << sv << '\n'; // Terminal
#10. Remove the first 8 characters
sv.remove_prefix(8);
std::cout << sv << '\n'; // 'Root'
You can also use string_view_literals
by adding the term sv
to the end, example code with literal:
#include <iostream>
#include <string_view>
using namespace std::string_view_literals;
int main(){
auto literal = "Terminal Root"sv;
std::cout << literal << '\n';
return 0;
}
Example of a ready code:
#include <iostream>
#include <string_view>
int main() {
constexpr std::string_view unicode[] {
"▀▄─", "▄▀─", "▀─▄", "▄─▀"
};
for (int y{}, p{}; y != 6; ++y, p = ((p + 1) % 4)) {
for (int x{}; x != 16; ++x)
std::cout << unicode[p];
std::cout << '\n';
}
}
Saída:
▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─
▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─
▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄
▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀
▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─▀▄─
▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─▄▀─
Some other functions are only available in C++20 or C++23, examples: contains()
, starts_with()
and others.
For more information visit: https://en.cppreference.com/w/cpp/string/basic_string_view .