8.5 — String tools
Read one box at a time. No rush.
Strings are lists of characters#
A std::string works a lot like a vector of chars.
C++
std::string word { "hello" };std::cout << word[0]; // hstd::cout << word.length(); // 5 for (char c : word) std::cout << c << '-'; // h-e-l-l-o-Handy string functions#
| Code | What it does | Example result |
|---|---|---|
s.length() / s.size() | number of characters | 5 |
s.empty() | is it empty? | false |
s + t / s += t | join text | "hello world" |
s.substr(1, 3) | 3 chars starting at index 1 | "ell" |
s.find("ll") | where "ll" starts | 2 |
s.replace(0, 1, "J") | swap 1 char at 0 for "J" | "Jello" |
s.at(i) / s[i] | one character | 'e' |
std::toupper(c) | uppercase one char (<cctype>) | 'H' |
Searching text#
find returns the position, or std::string::npos if it's not there:
C++
std::string text { "I like C++" }; if (text.find("C++") != std::string::npos){ std::cout << "Found it!\n";}Reading a whole line#
std::cin >> s stops at a space. std::getline reads everything up to Enter:
C++
std::string sentence {};std::getline(std::cin >> std::ws, sentence);Numbers ↔ text#
C++
int n { std::stoi("123") }; // "123" -> 123double d { std::stod("2.5") }; // "2.5" -> 2.5std::string s { std::to_string(42) }; // 42 -> "42"Tip: press ← / → to move between lessons, / to search.