Use string_view as a lightweight string object
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 you 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...
 
                                             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
     
         
                 
                 
                 
                 
                 
                 
                 
                 
                