C++ String Functions - Cheat Sheet
| Function | Description |
Example Code | Output
|
|---------------------|-------------------------------------------------------|----
-----------------------------------------------------|-----------------------------
-------|
| length() / size() | Returns the length of the string |
string s = "Hello"; cout << s.length(); | 5
|
| empty() | Checks if the string is empty |
string s = ""; cout << s.empty(); | 1 (true)
|
| at(index) | Returns character at specified index |
string s = "Hello"; cout << s.at(1); | e
|
| front() | Returns the first character |
string s = "Hello"; cout << s.front(); | H
|
| back() | Returns the last character |
string s = "Hello"; cout << s.back(); | o
|
| append() | Appends to the string |
string s = "Hello "; s.append("World"); cout << s; | Hello World
|
| push_back() | Adds character at the end |
string s = "Hi"; s.push_back('!'); cout << s; | Hi!
|
| pop_back() | Removes last character |
string s = "Hi!"; s.pop_back(); cout << s; | Hi
|
| substr(pos, len) | Returns substring |
string s = "Hello"; cout << s.substr(1, 3); | ell
|
| compare() | Compares strings |
string a = "abc", b = "xyz"; cout << a.compare(b); | Negative value (a < b)
|
| find() | Finds substring/index |
string s = "hello"; cout << s.find("lo"); | 3
|
| rfind() | Finds last occurrence |
string s = "abcabc"; cout << s.rfind("a"); | 3
|
| erase(pos, len) | Erases part of string |
string s = "hello"; s.erase(1, 2); cout << s; | hlo
|
| insert(pos, str) | Inserts string at position |
string s = "heo"; s.insert(2, "ll"); cout << s; | hello
|
| replace(pos, len, str) | Replaces part with another string | string
s = "hello"; s.replace(1, 2, "i"); cout << s; | hilo
|
| to_string() | Converts number to string | int x
= 10; cout << to_string(x); | "10"
|
| stoi() | Converts string to integer |
string s = "123"; cout << stoi(s); | 123
|
| getline() | Reads full line with spaces |
getline(cin, s); | [Reads input including
spaces] |