Course outline · 0% complete

0/27 lessons0%

Course overview →

std::string, Deeply

lesson 8-2 · ~12 min · 21/27

A large share of interview problems are string problems — parsing, palindromes, anagrams, tokenizing — and in production, text handling is where C's raw char arrays with manual length tracking caused decades of buffer-overflow security bugs. std::string exists to close that hole: it owns its memory, knows its size, and grows on demand.

A string is a vector of chars, with extras

std::string manages a heap character array with RAII, just like vector, and shares its interface: s.size(), s[i], s.empty(), s.push_back('x'), s.back(). On top of that:

std::string s = "hello";

s + " world"        // concatenation (makes a new string)
s += "!";           // append in place
s.substr(1, 3)      // "ell" : from index 1, take 3 chars
s.find("ll")        // 2 : index of first match
s.find("zz")        // std::string::npos : the not-found marker
s == "hello"        // true : compares contents
std::to_string(42)  // "42"
std::stoi("42")     // 42

Characters are small numbers

s[i] is a char, and chars are integers underneath (their ASCII codes). That enables interview-favorite arithmetic:

char c = 'b';
c - 'a'             // 1 : position in the alphabet
char(c + 1)         // 'c'
'5' - '0'           // 5 : digit character to number

Reading strings

std::cin >> word reads ONE whitespace-delimited word (lesson 1-2). To read a whole line, spaces included, use std::getline(std::cin, line).

Code exercise · cpp

Run this string workout: slicing, searching, and char arithmetic.

Quiz

What does the expression `'7' - '0'` evaluate to?

Code exercise · cpp

Your turn. Read one word and print it reversed, then print its vowel count (a, e, i, o, u). Input is `algorithm`, so expected output is `mhtirogla` then `vowels: 3`.

Code exercise · cpp

Your turn: count the vowels in the string with an index loop and the comparison chain. "encyclopedia" contains 5 (e, o, e, i, a).