C++ String Views
A string view is a light look at text stored somewhere else. It reads the text without owning it and without copying it.
A view over a string
A view is set from the string here. It prints the same text, and its size counts the same characters.
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string name = "Hana Kim";
std::string_view view = name;
std::cout << view << "\n";
std::cout << view.size() << "\n";
return 0;
}One function, three kinds of text
The show function takes a view as its parameter. A string, a string literal, and a view each fit that one parameter.
#include <iostream>
#include <string>
#include <string_view>
void show(std::string_view text) {
std::cout << text << "\n";
}
int main() {
std::string word = "From string";
std::string_view view = "From view";
show(word);
show("From literal");
show(view);
return 0;
}Pieces of a view
substr takes the first five characters as a smaller view. remove_prefix then moves the start past the space.
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string text = "Hello World";
std::string_view view = text;
std::cout << view.substr(0, 5) << "\n";
view.remove_prefix(6);
std::cout << view << "\n";
return 0;
}Trimming the end of a view
remove_suffix pulls the end of the view back by four characters. The file ending falls out of the view, and the base name stays.
#include <iostream>
#include <string_view>
int main() {
std::string_view view = "Report.txt";
std::cout << view << "\n";
view.remove_suffix(4);
std::cout << view << "\n";
return 0;
}Example
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string full = "Hana Kim";
std::string_view view = full;
std::string_view first = view.substr(0, view.find(' '));
std::string_view last = view.substr(view.find(' ') + 1);
std::cout << "First: " << first << "\n";
std::cout << "Last: " << last << "\n";
return 0;
}Key points
- The <string_view> header gives a program the std::string_view type.
- A view holds a start position and a length.
- A view does not own the text it shows.
- A function that takes a view accepts a string, a string literal, and another view.
- substr on a view gives a smaller view of one piece.
- remove_prefix moves the start of a view forward, and remove_suffix pulls its end back.
In this example, one view covers the full name. find gives the position of the space, and two substr calls split the view at that position. The pieces print as the first name and the last name.
Note
The text behind a view must stay alive for as long as the view is used.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does a string view hold?