C++ std::string Functions Cheat Sheet
1. Creation & Initialization
----------------------------
string s1 = "Hello";
string s2("World");
string s3(s1); // copy
string s4(5, 'x'); // "xxxxx"
2. Input & Output
-----------------
cin >> s1; // until space
getline(cin, s1); // full line
cout << s1 << endl;
3. Size & Capacity
------------------
s1.size(); // length
s1.length(); // same as size()
s1.empty(); // check empty
s1.clear(); // clear string
4. Accessing Characters
-----------------------
s1[0]; // first char
s1.at(0); // first char (bounds check)
s1.front(); // first char
s1.back(); // last char
5. Modifying Strings
--------------------
s1 += " World"; // append
s1.append("!!!"); // append
s1.push_back('A'); // add char
s1.pop_back(); // remove last char
s1.insert(3, "XYZ"); // insert at index
s1.erase(2, 4); // erase from index
s1.replace(2, 3, "abc"); // replace chars
reverse(s1.begin(), s1.end()); // reverse
6. Searching
------------
s1.find("llo"); // index or npos
s1.rfind("l"); // from end
s1.find_first_of("aeiou"); // first vowel
s1.find_last_of("aeiou"); // last vowel
s1.find_first_not_of("abc"); // first not abc
7. Substrings
-------------
string s2 = s1.substr(2); // from index 2
Page 1
C++ std::string Functions Cheat Sheet
string s3 = s1.substr(2, 4); // length 4
8. Comparison
-------------
if (s1 == s2) { }
if (s1.compare(s2) == 0) { }
9. Conversion
-------------
string numStr = "123";
int x = stoi(numStr);
long y = stol(numStr);
double d = stod("3.14");
int num = 456;
string s = to_string(num);
10. Iteration
-------------
for (char c : s1) cout << c << " ";
for (int i = 0; i < s1.size(); i++) cout << s1[i];
Tip: Use ios::sync_with_stdio(false); cin.tie(nullptr); for speed.
Page 2