<string> Member Functions Reference
The std::string class manages text for you: growth, storage, destruction, the whole package. Here are the member functions you'll need.
Size and capacity
| Function | Example | What it does |
|---|
length() | s.length() | number of characters total |
size() | s.size() | same as length(), same letters |
capacity() | s.capacity() | characters the string can hold in its current memory |
empty() | s.empty() | true if the string has zero characters |
clear() | s.clear() | remove all characters, size becomes 0 |
reserve(n) | s.reserve(30) | pre-allocate memory for at least n chars |
resize(n) | s.resize(10) | force the size to n, fill new chars with '\0' |
Access a single character
| Function | Example | Notes |
|---|
at(n) | s.at(0) | bounds-checked; throws out_of_range on bad index |
operator[] | s[0] | no bounds check - faster, but your job to stay in range |
front() | s.front() | first character |
back() | s.back() | last character |
Editing the text
| Function | Example | What it does |
|---|
append | s.append("word") | add text to the end (same as +=) |
insert | s.insert(2, "XX") | insert text at position 2 |
replace | s.replace(3, 2, "YZ") | replace 2 chars starting at index 3 with "YZ" |
erase | s.erase(2, 3) | remove 3 chars starting at index 2 |
push_back | s.push_back('X') | add one character at the end |
pop_back | s.pop_back() | remove the last character (C++11) |
Search and slicing
| Function | Example | What it returns |
|---|
find | s.find("needle") | index of the first niche or npos if not found |
substr | s.substr(3, 2) | a shorter string cut from the string |
npos is a special "not found" size_t value. Always compare: if (s.find("x") != string::npos).
substr(3) without a length grabs the rest.
Comparing and converting
| Function | Example | What it does |
|---|
compare | s.compare(t) | <0 if smaller, 0 if equal, >0 if bigger (dictionary order) |
c_str() | s.c_str() | C-style char pointer version (NUL-terminated, const) |
data() | s.data() | pointer to the character data (no NUL guarantee before C++11) |
Free functions for conversions
| Function | Example | What it does |
|---|
to_string | to_string(42) | turns a number into a string |
stoi | stoi("42") | converts a string to int |
stod | stod("3.14") | converts a string to double |
stol | stol("123456") | converts a string to long |
These live in the std namespace too; you'll already have them after including <string>.
Notes
find returns string::npos (a huge number) when nothing is found - compare, don't assume.at checks bounds and throws; [] is faster and trusts you.substr creates a new string; it does not copy the original.- Strings auto-grow when you append during use - no manual resize needed.
TL;DR
- Size:
length()/size()/empty(); manage room with reserve()/resize(). - Edit:
append/insert/replace/erase/push_back/pop_back. - Find
find + substr to locate and cut text. - Convert with
to_string / stoi / stod.