Site

Strings — std::string and string_view

Tutorial S1.0  •  C++ / Learn / StdLib

S1.0 What This Teaches

C++ has two main string abstractions. This tutorial covers:

S1.1 std::string vs std::string_view

std::stringstd::string_view
Owns datayesno
Mutableyesno
Heap allocationyes (for long strings)no
Can be null-terminatedalwaysnot guaranteed
Use forstoring and modifying textread-only parameter, substring
Pass function parameters that only need to read a string as std::string_view - it accepts both std::string and string literals without a copy.

S1.2 Construction

std::string s1 = "Hello, World!";
std::string s2("Hello");
std::string s3(5, '*');   // "*****" - 5 copies of '*'
std::string s4;           // empty string

S1.3 Concatenation

std::string a = "Hello";
std::string b = ", World!";
std::string c = a + b;    // creates new string
a += "!";                 // append in place

// string literal + string (not literal + literal)
std::string greeting = std::string("Hello") + ", " + "World!";
Two string literals cannot be concatenated with + - at least one operand must be a std::string.

S1.4 Query Methods

std::string s = "Hello, World!";
s.length();    // 13
s.size();      // same as length()
s.empty();     // false
s.front();     // 'H'
s.back();      // '!'
s[0];          // 'H' - unchecked
s.at(0);       // 'H' - throws std::out_of_range if index invalid

S1.5 Searching and Substrings

std::string s = "Hello, World!";

size_t pos = s.find("World");   // 7; returns std::string::npos if not found
if (pos != std::string::npos)
    std::cout << "found at " << pos << "\n";

std::string sub = s.substr(7, 5);   // "World" - start pos, length
bool starts = s.starts_with("Hello");  // C++20
bool ends   = s.ends_with("!");        // C++20

S1.6 Modification

std::string s = "Hello, World!";
s.replace(7, 5, "C++");   // "Hello, C++!"
s.insert(5, " there");    // "Hello there, C++!"
s.erase(5, 6);            // remove " there"

// individual characters
s[0] = 'h';
for (char& c : s) c = static_cast<char>(std::toupper(c));

S1.7 Converting to and from Numbers

int    n = std::stoi("42");      // string to int
long   l = std::stol("100");     // string to long
double d = std::stod("3.14");    // string to double

std::string ns = std::to_string(123);    // int to string
std::string ds = std::to_string(3.14);   // double to string
std::stoi throws std::invalid_argument if the string is not a valid number and std::out_of_range if the value overflows. Wrap in try/catch when the input is untrusted.

S1.8 Example - All Together

// Strings - std::string and std::string_view operations.

#include <iostream>
#include <string>
#include <string_view>

int main() {
    std::string s = "Hello, World!";
    std::cout << s.length() << "\n";               // 13

    std::string t = s.substr(0, 5) + " C++!";
    std::cout << t << "\n";                          // Hello C++!

    size_t pos = s.find("World");
    std::cout << "World at: " << pos << "\n";       // 7

    s.replace(7, 5, "C++");
    std::cout << s << "\n";                          // Hello, C++!

    std::string_view sv = s;
    std::cout << sv.substr(0, 5) << "\n";           // Hello

    std::cout << std::stoi("42") + 1 << "\n";       // 43
    std::cout << std::to_string(100) << "\n";       // 100
    return 0;
}
13
Hello C++!
World at: 7
Hello, C++!
Hello
43
100

S1.9 Exercise

Exercise
  • Write a function count_vowels(std::string_view s) that returns the number of vowels in the string.
  • Write a function reverse_words(const std::string& s) that returns the words in reversed order (e.g., "Hello World" → "World Hello").
  • Parse the string "name=Alice,age=30" by splitting on ',' and then on '=' to extract the key-value pairs and print them.

S1.10 Common Mistakes

Concatenating two string literals

auto s = "Hello" + ", World!";   // error: pointer arithmetic, not concatenation
Wrap one literal in std::string(...) first.

string_view outliving the string it views

std::string_view get_view() {
    std::string s = "hello";
    return s;    // dangling: s is destroyed, view points to freed memory
}
A string_view is only valid as long as the underlying string is alive.

Using find result without checking npos

size_t pos = s.find("xyz");
std::string sub = s.substr(pos, 3);   // undefined behavior if find returned npos

S1.11 Key Terms

TermMeaning
std::stringOwning, heap-managed, mutable string
std::string_viewNon-owning read-only view of character data; no allocation
length() / size()Number of characters (excluding null terminator)
find()Returns position of substring, or std::string::npos if not found
nposSentinel value returned by find when no match exists; equals SIZE_MAX
substr(pos, len)Returns a new string starting at pos with len characters
std::stoi / stodParse string to int / double; throw on invalid input
std::to_stringConvert numeric type to std::string