String in C++ - Competitive Programming Cheatsheet
1. Declaring a String
#include <iostream>
#include <string>
using namespace std;
int main() {
string s; // empty string
cin >> s; // input (reads till space)
cout << s << "\n"; // output
2. Reverse a String
reverse([Link](), [Link]());
3. Sort a String
sort([Link](), [Link]());
4. Count Characters (Example: Count 'a')
int count = 0;
for (char c : s) {
if (c == 'a') count++;
5. String to Integer
int x = stoi(s);
6. Integer to String
string s = to_string(x);
7. Iterate Over a String
for (int i = 0; i < [Link](); i++) {
cout << s[i] << " ";
}
// or range-based:
for (char c : s) {
cout << c << " ";
8. Take Full Line Input
getline(cin, s); // takes full line including spaces
9. Substring of a String
string part = [Link](start_index, length);
10. Find Substring
if ([Link]("abc") != string::npos) {
// found!
11. Erase Part of a String
[Link](start_index, count);
12. Insert in a String
[Link](pos, "xyz");
13. Compare Strings
if (s1 == s2) cout << "Equal";
if (s1 < s2) cout << "Lexicographically smaller";
14. Remove Duplicates (after sorting)
sort([Link](), [Link]());
[Link](unique([Link](), [Link]()), [Link]());
15. Fast Input/Output for CP
ios::sync_with_stdio(false);
[Link](NULL);