logo

C++ - Strings

std::string is mutable

Strings in many languages are immutable (e.g. Java, Go). But std::string in C++ is mutable.

std::string my_string = "Hello";
std::cout << my_string << std::endl; // Output: Hello

my_string += ", World!";
std::cout << my_string << std::endl; // Output: Hello, World!

my_string.replace(0, 5, "Greetings");
std::cout << my_string << std::endl; // Output: Greetings, World!

String literals are immutable

const char* string_literal = "Hello";
// string_literal[0] = 'h'; // Error: Cannot modify a string literal

std::string_view is immutable

A string_view is a reference to a piece of text data stored elsewhere, essentially it is a pair of "(pointer-to-first-element, size)".

// From a string literal
std::string_view sv1 = "Hello, world!";

// From a std::string
std::string str = "Hello, world!";
std::string_view sv2 = str;

// Substring view
std::string_view sv3 = sv1.substr(0, 5);

To convert a std::string_view to a std::string:

std::string_view sv = "...";
std::string str = std::string(sv);

When to use std::string and std
?

  • Use std::string
    • when it needs to fully own the string, or the underlying data may go out of scope.
      • For example, when storing string data in a struct, you should probably use std::string, unless you know the underlying string of std::string_view is alive for the whole lifecycle of your struct.
    • when modiying the string is necessary.
  • Use std::string_view
    • when it is read-only.
    • when the underlying data is guaranteed to outlive the string_view.