R.2 — string functions

📘 Appendix R⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

All need #include <string>.

CodeWhat it does
s.length() / s.size()number of characters
s.empty()true if no characters
s[i] / s.at(i)one character (at checks the index)
s + t, s += tjoin text
s.substr(start, count)part of the text
s.find(t)position of t, or std::string::npos
s.replace(pos, count, t)replace part of the text
s.insert(pos, t)insert t at pos
s.erase(pos, count)remove characters
s.front() / s.back()first / last character
s.clear()make it empty
std::stoi(s) / std::stod(s)text → int / double
std::to_string(n)number → text
C++
std::string s { "Hello, world" };std::cout << s.substr(7, 5);   // worldstd::cout << s.find("o");      // 4

Character tools#

Need #include <cctype>.

CodeWhat it does
std::isdigit(c)is it 0–9?
std::isalpha(c)is it a letter?
std::isspace(c)is it a space, tab or new line?
std::toupper(c) / std::tolower(c)change case
Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.