C++ Tutorial: Strings
std::string — methods, concatenation, getline, string operations, string_view, and C-strings vs std::string.
Text in C++
C++ has two string types: the ancient C-string (`char array`) and the modern `std::string`. Always use `std::string` — it manages memory automatically and has a rich API.
`string_view` (C++17) is the efficient read-only alternative — it avoids copies when you just need to look at string data.
What you'll learn in this C++ strings tutorial
This interactive C++ tutorial has 7 hands-on exercises. Estimated time: 18 minutes.
- std::string basics — `#include <string>` gives you `std::string`.
- substr, find, replace — String operations:
- String comparison and case — C++ strings compare lexicographically with `==`, `<`, `>`, `<=`, `>=`.
- to_string and stoi — convert between types — Convert between strings and numbers:
- stringstream — build and parse — `stringstream` from `<sstream>` builds strings like cout, and parses like cin:
- string_view — efficient read-only strings — `string_view` (C++17) is a lightweight, non-owning reference to string data — no copy, no allocation:
- Build a word analyser — No starter code.
C++ Strings concepts covered
- Text in C++