Strings & Text

Scope: Text processing is a large share of real software. C++ handles text with std::string, a safe, growable container. This lesson teaches its basics, common operations, console input, the zero-copy std::string_view, and number formatting.

std::string basics

std::string (from the <string> header) stores a sequence of characters. Unlike the old C-style arrays, it manages its own memory and knows its length. It grows automatically when you add characters.

Initialization

#include <string>

std::string name = "Ada";            // from a string literal
std::string greeting = "Hello, " + name;   // concatenation at creation
std::string empty;                   // an empty string ""

The + operator concatenates two strings. Ensure at least one side is a std::string — mixing a literal with a literal is not allowed: "a" + "b" is a compile error.

Common operations

std::string provides a rich API. The members you will use most are shown below with short comments; the standard library lesson covers iterating and algorithms.

Size and access

std::string word = "hello";
std::cout << word.size();     // 5 — number of characters
std::cout << word[0];         // 'h' — first character (like arrays)
word[4] = '!';                // word becomes "hell!"
std::cout << word.back();     // '!' — last character (C++11)

Empty-string checks are a common source of bugs — word.empty() is the readable test, and it is faster than comparing size() == 0.

Concatenation and comparison

std::string a = "C++";
std::string b = " is fun";
std::string c = a + b;          // "C++ is fun"
a += "!";                       // a becomes "C++!"

bool same = (a == "C++!");      // strings compare with == and !=
bool order = (b < "zebra");     // lexicographic (dictionary) order

Comparisons work the way you expect from a dictionary: "apple" < "banana" is true. You can also find and extract text:

std::string text = "I love C++";
std::size_t pos = text.find("C++");      // 7 — index of the match
std::string sub = text.substr(7, 3);     // "C++" — 3 chars from index 7
std::cout << (pos == std::string::npos ? "not found" : "found");

When find finds nothing it returns the special value std::string::npos — always check for it before using the position.

Reading text input

std::cin reads from the console. The stream operator >> stops at whitespace, so it reads one word at a time; std::getline reads a whole line, spaces included.

#include <iostream>
#include <string>

int main() {
    std::string first, last;
    std::cout << "First name? ";
    std::cin >> first;                    // reads one word
    std::cout << "Full name? ";
    std::getline(std::cin, last);         // reads until Enter
    std::cout << "Hi " << first << " " << last << "\n";
    return 0;
}

After >>, the input buffer still holds the newline; a following getline would read an empty line. The fix is std::cin.ignore() between them — a classic beginner trap that every C++ developer has met.

std::string_view

std::string_view (C++17) is a borrowed view of characters: it does not own or copy the text. Use it for function parameters that only read a string — zero allocation cost.

#include <string_view>

std::size_t count_vowels(std::string_view text) {   // no copy
    std::size_t n = 0;
    for (char ch : text) {
        if (ch == 'a' || ch == 'e' || ch == 'i' ||
            ch == 'o' || ch == 'u') {
            n++;
        }
    }
    return n;
}

A view is a borrow — the underlying text must outlive the view. Never return a string_view to a local string.

Formatting output

For aligned numbers and tables, the <iomanip> manipulators control width and decimals:

#include <iomanip>

double pi = 3.14159265;
std::cout << std::fixed << std::setprecision(2) << pi << "\n";   // 3.14
std::cout << std::setw(8) << pi << "\n";                        // right-aligned in 8 columns

C++20 adds the safer std::format, similar to Python's f-strings — you will meet it in the modern C++ lesson.

Practice

  1. Read a full name from the user and print "Hello, !" with getline.
  2. Count how many times the letter 'a' appears in a sentence.
  3. Reverse a string using a loop and compare it with the original.
  4. Split a comma-separated list like "red,green,blue" into three substrings using find and substr.
  5. Print a temperature table with setw and setprecision for five values.