Use string_view as a Lightweight String Object
Learn to use string_view as a lightweight string object.
We'll cover the following...
The string_view class provides a lightweight alternative to the string class. Instead of maintaining its own data store, string_view operates on a view of a C-string. This makes string_view smaller and more efficient than std::string. It's useful in cases where we need a string object but don't need the more memory- and computation-intensive features of std::string.
How to do it
The string_view class looks deceptively similar to the STL string class, but it works a bit differently. Let's consider some examples:
Here's an STL
stringinitialized from a C-string (array ofchar):
char text[]{ "hello" };string greeting{ text };text[0] = 'J';cout << text << ' ' << greeting << '\n';
Output:
Jello hello
Notice that the string does not change when we modify the array. This is because the string constructor creates its own copy of the underlying data.
When we do the same with a
string_view, we get a different ...