[c++] std::string_view
In C++, std::string_view
is a non-owning view to a sequence of characters. It is part of the C++17 standard and is used to represent a read-only view of a std::string
or a portion of a char
array. This can be useful in scenarios where you don’t want to create a copy of the original string, but rather work with a view of it.
Features of std::string_view
- Non-owning:
std::string_view
does not own the underlying data, it simply refers to an existing string or character array. - Lightweight: Because it’s just a view and doesn’t make a copy of the data, it’s lightweight and efficient.
- Null-terminated strings: It supports both null-terminated and non-null-terminated strings.
Example Usage
#include <iostream>
#include <string_view>
void printStringView(std::string_view sv) {
std::cout << "Length: " << sv.length() << ", Data: " << sv << std::endl;
}
int main() {
std::string str = "Hello, world!";
std::string_view sv(str);
printStringView(sv); // Output: Length: 13, Data: Hello, world!
// Substring
std::string_view svSub = sv.substr(7, 5); // "world"
printStringView(svSub); // Output: Length: 5, Data: world
return 0;
}