50+ useful C++ functions ✅✅
Here are 50+ useful C++ string functions and related STL utilities that are commonly used in DSA and interviews.
| Function | Purpose | Example |
|---|---|---|
size() | Length of string | s.size() |
length() | Same as size | s.length() |
empty() | Check empty | s.empty() |
clear() | Remove all characters | s.clear() |
push_back(ch) | Add character at end | s.push_back('a') |
pop_back() | Remove last character | s.pop_back() |
append(str) | Append string | s.append("abc") |
append(n,ch) | Append same character | s.append(5,'*') |
+= | Append | s += "abc" |
+ | Concatenate | a+b |
insert(pos,str) | Insert string | s.insert(2,"abc") |
erase(pos,len) | Delete substring | s.erase(2,3) |
replace(pos,len,str) | Replace substring | s.replace(1,2,"xy") |
substr(pos,len) | Extract substring | s.substr(2,4) |
find(str) | First occurrence | s.find("ab") |
rfind(str) | Last occurrence | s.rfind("ab") |
find_first_of(ch) | First matching char | s.find_first_of('a') |
find_last_of(ch) | Last matching char | s.find_last_of('a') |
find_first_not_of(ch) | First different char | s.find_first_not_of(' ') |
find_last_not_of(ch) | Last different char | s.find_last_not_of(' ') |
compare(str) | Compare strings | s.compare(t) |
at(i) | Character with bounds check | s.at(3) |
front() | First character | s.front() |
back() | Last character | s.back() |
begin() | Iterator begin | s.begin() |
end() | Iterator end | s.end() |
rbegin() | Reverse begin | s.rbegin() |
rend() | Reverse end | s.rend() |
resize(n) | Resize string | s.resize(10) |
swap(str) | Swap strings | s.swap(t) |
copy() | Copy chars to array | s.copy(arr,n) |
c_str() | Convert to C-string | s.c_str() |
data() | Pointer to characters | s.data() |
capacity() | Current capacity | s.capacity() |
reserve(n) | Reserve memory | s.reserve(100) |
shrink_to_fit() | Reduce capacity | s.shrink_to_fit() |
string a = "abc";
string b = "abd";
if (a.compare(b) == 0)
cout << "Equal";
else if (a.compare(b) < 0)
cout << "a is smaller";
else
cout << "a is greater";auto vs auto& (Short Explanation)
auto (Copy)
- Creates a copy of each element.
- Changes do not affect the original container.
- Use when you only need to read values or don't mind copying.
Example
vector<int> nums = {1, 2, 3};
for (auto x : nums)
x++;
cout << nums[0];Output
1x is a copy, so nums remains unchanged.
auto& (Reference)
- Refers to the original element (no copy).
- Changes do affect the original container.
- Faster for large objects (
string,map,vector<string>). - Use when you want to modify elements or avoid unnecessary copying.
Example
vector<int> nums = {1, 2, 3};
for (auto &x : nums)
x++;
cout << nums[0];Output
2x is a reference, so nums is modified.
Quick Rule
auto | auto& |
|---|---|
| Makes a copy | Uses the original element (reference) |
| Original data doesn't change | Original data changes |
| Good for reading | Good for modifying or avoiding copies |
Remember
- Read only →
auto - Modify or avoid copying →
auto&
Character Functions (<cctype>)
| Function | Purpose |
|---|---|
tolower(ch) | Lowercase |
toupper(ch) | Uppercase |
islower(ch) | Lowercase? |
isupper(ch) | Uppercase? |
isdigit(ch) | Digit? |
isalpha(ch) | Alphabet? |
isalnum(ch) | Letter/Digit? |
isspace(ch) | Space? |
ispunct(ch) | Punctuation? |
isprint(ch) | Printable? |
iscntrl(ch) | Control character? |
isxdigit(ch) | Hex digit? |
STL Algorithms (<algorithm>)
| Function | Purpose |
|---|---|
reverse() | Reverse string |
sort() | Sort characters |
transform() | Convert upper/lower |
count() | Count character |
count_if() | Count by condition |
find() | Find character |
all_of() | All satisfy condition |
any_of() | Any satisfy condition |
none_of() | None satisfy condition |
unique() | Remove consecutive duplicates |
rotate() | Rotate string |
next_permutation() | Next permutation |
prev_permutation() | Previous permutation |
min_element() | Smallest character |
max_element() | Largest character |
Conversion Functions
| Function | Purpose |
|---|---|
stoi() | String → int |
stol() | String → long |
stoll() | String → long long |
stof() | String → float |
stod() | String → double |
to_string() | Number → string |
String Stream (<sstream>)
| Function | Purpose |
|---|---|
stringstream ss(s) | Create stream |
getline(ss,word,' ') | Read until delimiter |
ss >> word | Read word |
ss << x | Write to stream |
Frequently Used in DSA
| Function | Example |
|---|---|
| Reverse string | reverse(s.begin(), s.end()); |
| Sort string | sort(s.begin(), s.end()); |
Count 'a' | count(s.begin(), s.end(), 'a'); |
| Lowercase | transform(s.begin(), s.end(), s.begin(), ::tolower); |
| Uppercase | transform(s.begin(), s.end(), s.begin(), ::toupper); |
| Palindrome check | reverse(t.begin(), t.end()); |
| Split words | stringstream ss(s); |
| Find substring | s.find("abc") |
| Remove substring | s.erase(pos, len) |
| Replace substring | s.replace(pos, len, "xyz") |
C++ string Functions — With Examples
#include <bits/stdc++.h>
using namespace std;
int main() {
string s = "hello";
string t = "world";
}1. Basic String Functions
| Function | Purpose | Example |
|---|---|---|
size() | Length | s.size() |
length() | Length | s.length() |
empty() | Check empty | s.empty() |
clear() | Remove all | s.clear() |
push_back() | Add character | s.push_back('!') |
pop_back() | Remove last character | s.pop_back() |
append() | Add string | s.append("abc") |
+= | Add string | s += "abc" |
+ | Concatenate | a + b |
Examples
string s = "hello";
cout << s.size(); // 5
cout << s.length(); // 5
cout << s.empty(); // 0 (false)
s.push_back('!');
cout << s; // hello!
s.pop_back();
cout << s; // hello
s.append(" world");
cout << s; // hello world
s += "!";
cout << s; // hello world!
string a = "Hello ";
string b = "World";
string c = a + b;
cout << c; // Hello World2. Insert, Erase, Replace, Substring
insert()
Adds characters at a particular position.
string s = "hello";
s.insert(2, "ABC");
cout << s;Output:
heABClloPosition 2 means insertion happens before index 2.
erase()
Removes characters.
string s = "abcdef";
s.erase(2, 3);
cout << s;Output:
abfMeaning:
erase(start, length)
erase(2, 3)Removes:
c d ereplace()
Replace part of a string.
string s = "I like Java";
s.replace(7, 4, "C++");
cout << s;Output:
I like C++Syntax:
s.replace(start, length, newString);substr()
Extract a substring.
string s = "abcdefgh";
string x = s.substr(2, 4);
cout << x;Output:
cdefSyntax:
s.substr(start, length);Very common DSA use
string s = "leetcode";
if (s.substr(0, 4) == "leet")
cout << "Matched";3. Searching Functions
find()
Find first occurrence.
string s = "hello world";
cout << s.find("world");Output:
6Important
If not found:
if (s.find("xyz") == string::npos)
cout << "Not found";rfind()
Find last occurrence.
string s = "abcabc";
cout << s.rfind("abc");Output:
3find_first_of()
Find first character that belongs to a set.
string s = "hello123";
cout << s.find_first_of("0123456789");Output:
5First digit is at index 5.
find_last_of()
Find last matching character.
string s = "hello123";
cout << s.find_last_of("0123456789");Output:
7find_first_not_of()
Find first character that is not from the given set.
string s = " hello";
cout << s.find_first_not_of(' ');Output:
3Useful for removing/skipping spaces.
find_last_not_of()
Find last character that is not from the given set.
string s = "hello ";
cout << s.find_last_not_of(' ');Output:
44. Comparing Strings
compare()
string a = "abc";
string b = "abd";
if (a.compare(b) == 0)
cout << "Equal";
else if (a.compare(b) < 0)
cout << "a is smaller";
else
cout << "a is greater";Output:
a is smallerQuick rule
compare() == 0 → equal
compare() < 0 → smaller
compare() > 0 → greater5. Character Access
at()
string s = "hello";
cout << s.at(1);Output:
eat() performs bounds checking.
front()
string s = "hello";
cout << s.front();Output:
hback()
string s = "hello";
cout << s.back();Output:
o6. Iterators
begin() and end()
string s = "abc";
for (auto it = s.begin(); it != s.end(); it++)
cout << *it;Output:
abcrbegin() and rend()
Used for reverse traversal.
string s = "abc";
for (auto it = s.rbegin(); it != s.rend(); it++)
cout << *it;Output:
cba7. Resize and Swap
resize()
string s = "hello";
s.resize(3);
cout << s;Output:
helYou can also increase the size:
string s = "abc";
s.resize(5, 'x');
cout << s;Output:
abcxxswap()
string a = "hello";
string b = "world";
a.swap(b);
cout << a << " " << b;Output:
world hello8. Memory-Related Functions
These are less frequently used in normal DSA.
capacity()
string s = "hello";
cout << s.capacity();Returns the currently allocated storage capacity.
reserve()
Reserve memory beforehand.
string s;
s.reserve(100);
cout << s.capacity();Useful when you know the string will become large.
shrink_to_fit()
Request reduction of unused capacity.
string s = "hello";
s.reserve(100);
s.shrink_to_fit();c_str()
Get C-style string.
string s = "hello";
const char* p = s.c_str();
cout << p;Output:
hellodata()
Access underlying character data.
string s = "hello";
cout << s.data();Output:
hello9. copy()
Copies characters into a character array.
string s = "hello";
char arr[10];
s.copy(arr, 3);
arr[3] = '\0';
cout << arr;Output:
helSyntax:
s.copy(array, numberOfCharacters, startPosition);10. Character Functions <cctype>
Include:
#include <cctype>tolower()
char ch = 'A';
cout << char(tolower(ch));Output:
atoupper()
char ch = 'a';
cout << char(toupper(ch));Output:
Aisdigit()
Check whether character is a digit.
char ch = '5';
if (isdigit(ch))
cout << "Digit";Output:
Digitisalpha()
char ch = 'A';
if (isalpha(ch))
cout << "Alphabet";isalnum()
Alphabet or digit.
char ch = '7';
if (isalnum(ch))
cout << "Alphanumeric";islower()
char ch = 'a';
cout << islower(ch);isupper()
char ch = 'A';
cout << isupper(ch);isspace()
char ch = ' ';
if (isspace(ch))
cout << "Space";ispunct()
Checks punctuation.
char ch = '!';
if (ispunct(ch))
cout << "Punctuation";isprint()
char ch = 'A';
if (isprint(ch))
cout << "Printable";isxdigit()
Checks hexadecimal digit.
char ch = 'F';
if (isxdigit(ch))
cout << "Hex digit";11. STL Algorithms for Strings
Include:
#include <algorithm>reverse()
string s = "hello";
reverse(s.begin(), s.end());
cout << s;Output:
ollehDSA use
Palindrome:
string t = s;
reverse(t.begin(), t.end());
if (s == t)
cout << "Palindrome";12. sort()
string s = "dcba";
sort(s.begin(), s.end());
cout << s;Output:
abcdVery common DSA use
Anagram:
string a = "listen";
string b = "silent";
sort(a.begin(), a.end());
sort(b.begin(), b.end());
if (a == b)
cout << "Anagram";13. count()
Count a particular character.
string s = "banana";
int cnt = count(s.begin(), s.end(), 'a');
cout << cnt;Output:
314. count_if()
Count according to a condition.
string s = "abc123";
int cnt = count_if(s.begin(), s.end(), ::isdigit);
cout << cnt;Output:
315. find()
STL find() can find an individual character.
string s = "hello";
auto it = find(s.begin(), s.end(), 'e');
if (it != s.end())
cout << "Found";16. all_of()
Check whether all characters satisfy a condition.
string s = "12345";
if (all_of(s.begin(), s.end(), ::isdigit))
cout << "All digits";Output:
All digits17. any_of()
Check whether at least one satisfies a condition.
string s = "abc1";
if (any_of(s.begin(), s.end(), ::isdigit))
cout << "Contains digit";Output:
Contains digit18. none_of()
Check whether none satisfy a condition.
string s = "abc";
if (none_of(s.begin(), s.end(), ::isdigit))
cout << "No digits";Output:
No digits19. transform()
Convert entire string to lowercase.
string s = "HELLO";
transform(s.begin(), s.end(), s.begin(), ::tolower);
cout << s;Output:
helloUppercase:
transform(s.begin(), s.end(), s.begin(), ::toupper);20. unique()
Removes consecutive duplicates.
string s = "aabbcc";
auto it = unique(s.begin(), s.end());
s.erase(it, s.end());
cout << s;Output:
abc⚠️ Important:
unique()does not remove all duplicates automatically.
Example:
aabbccabecomes:
abcabecause only consecutive duplicates are removed.
21. rotate()
string s = "abcdef";
rotate(s.begin(), s.begin() + 2, s.end());
cout << s;Output:
cdefab22. next_permutation()
string s = "abc";
next_permutation(s.begin(), s.end());
cout << s;Output:
acbUseful in permutation problems.
23. prev_permutation()
string s = "cba";
prev_permutation(s.begin(), s.end());
cout << s;Output:
cab24. min_element()
string s = "zebra";
auto it = min_element(s.begin(), s.end());
cout << *it;Output:
a25. max_element()
string s = "zebra";
auto it = max_element(s.begin(), s.end());
cout << *it;Output:
z26. String Conversion Functions
Include:
#include <string>stoi() — String → int
string s = "123";
int x = stoi(s);
cout << x + 10;Output:
133stol() — String → long
string s = "123456";
long x = stol(s);
cout << x;stoll() — String → long long
string s = "123456789123";
long long x = stoll(s);
cout << x;stof() — String → float
string s = "12.5";
float x = stof(s);
cout << x;stod() — String → double
string s = "12.3456";
double x = stod(s);
cout << x;to_string() — Number → String
int x = 123;
string s = to_string(x);
cout << s;Very common in DSA:
int n = 12345;
string s = to_string(n);
cout << s.size();27. stringstream
Include:
#include <sstream>Split sentence into words
string s = "I love C++";
stringstream ss(s);
string word;
while (ss >> word)
cout << word << endl;Output:
I
love
C++getline() with stringstream
string s = "apple,banana,mango";
stringstream ss(s);
string word;
while (getline(ss, word, ','))
cout << word << endl;Output:
apple
banana
mangoVery useful for splitting strings using a delimiter.
28. auto vs auto&
auto → Copy
vector<string> v = {"cat", "dog"};
for (auto x : v) {
x = "hello";
}
cout << v[0];Output:
catBecause x is a copy.
auto& → Original
vector<string> v = {"cat", "dog"};
for (auto &x : v) {
x = "hello";
}
cout << v[0];Output:
helloBecause x refers to the original element.
Easy rule
auto → copy
auto& → originalFor large objects:
for (auto &x : vectorOfStrings)avoids unnecessary copying.
If you're only reading and want to prevent copying, prefer:
for (const auto& x : vectorOfStrings)🔥 Most Important String Functions for DSA
You don't need to memorize all 50 equally. These are the ones you'll use constantly:
| Function | DSA Usage |
|---|---|
size() | String length |
empty() | Check empty |
push_back() | Add character |
pop_back() | Remove last |
substr() | Extract substring |
find() | Search substring |
erase() | Delete |
replace() | Replace |
compare() | Compare |
tolower() | Lowercase character |
toupper() | Uppercase character |
isdigit() | Check digit |
isalpha() | Check alphabet |
reverse() | Reverse |
sort() | Sorting / anagram |
count() | Frequency |
count_if() | Conditional count |
transform() | Convert case |
unique() | Remove consecutive duplicates |
all_of() | Validate all |
any_of() | Check at least one |
none_of() | Check none |
stoi() | String → int |
to_string() | Number → string |
stringstream | Split/process words |
⭐ DSA Cheat Sheet
// Length
s.size()
// Add / remove
s.push_back('a');
s.pop_back();
// Substring
s.substr(2, 4);
// Search
s.find("abc");
// Delete
s.erase(2, 3);
// Replace
s.replace(2, 3, "xyz");
// Reverse
reverse(s.begin(), s.end());
// Sort
sort(s.begin(), s.end());
// Count
count(s.begin(), s.end(), 'a');
// Lowercase
transform(s.begin(), s.end(), s.begin(), ::tolower);
// Uppercase
transform(s.begin(), s.end(), s.begin(), ::toupper);
// Number → String
string s = to_string(123);
// String → Number
int x = stoi("123");
// Split
stringstream ss(s);One important correction to your original table: find_first_of('a') is valid because there is a character overload, but the most commonly useful form is find_first_of("aeiou") when you want to search for any one of several characters.

