C++ Tutorial · C++ Basics · Lesson 5 of 21

C++ Strings

std::string operations, string_view and conversions.

std::string

std::string manages its own memory and grows as needed:

Example 1
#include <algorithm>
#include <iostream>
#include <string>
#include <string_view>

int main() {
    std::string s = "Hello";
    s += ", C++";
    std::cout << s << " (" << s.size() << " chars)\n";
    std::cout << s.substr(7) << ' ' << s.find("C++") << ' ' << s[0] << '\n';
    std::cout << std::boolalpha << s.starts_with("Hello") << ' ' << (s.find("C++") != std::string::npos) << '\n';
    s.replace(0, 5, "Goodbye");
    std::cout << s << '\n';
    std::string upper = s;
    std::transform(upper.begin(), upper.end(), upper.begin(), ::toupper);
    std::cout << upper << '\n';
    std::string_view view = s;
    std::cout << view.substr(0, 7) << ' ' << std::stoi("42") + 1 << ' ' << std::to_string(3.5) << '\n';
}

Output

Hello, C++ (10 chars)
C++ 7 H
true true
Goodbye, C++
GOODBYE, C++
Goodbye 43 3.500000

Run this on your computer — see “Get Started” for setup.

std::string_view

std::string_view is a lightweight, read-only view of characters — ideal for function parameters that only read a string, because it avoids copying.

Converting

std::to_string(42) turns numbers into strings; std::stoi and std::stod parse them (throwing on invalid input).

Test yourself

Which type gives a non-owning, read-only view of a string?

  1. std::string&
  2. std::string_view
  3. char*
  4. std::span
Show answer

Answer: std::string_view