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 string initialized from a C-string (array of char):

Get hands-on with 1200+ tech skills courses.