50+ useful C++ functions ✅✅

664
Jul 01, 2026
Aug 08, 2026

Here are 50+ useful C++ string functions and related STL utilities that are commonly used in DSA and interviews.

FunctionPurposeExample
size()Length of strings.size()
length()Same as sizes.length()
empty()Check emptys.empty()
clear()Remove all characterss.clear()
push_back(ch)Add character at ends.push_back('a')
pop_back()Remove last characters.pop_back()
append(str)Append strings.append("abc")
append(n,ch)Append same characters.append(5,'*')
+=Appends += "abc"
+Concatenatea+b
insert(pos,str)Insert strings.insert(2,"abc")
erase(pos,len)Delete substrings.erase(2,3)
replace(pos,len,str)Replace substrings.replace(1,2,"xy")
substr(pos,len)Extract substrings.substr(2,4)
find(str)First occurrences.find("ab")
rfind(str)Last occurrences.rfind("ab")
find_first_of(ch)First matching chars.find_first_of('a')
find_last_of(ch)Last matching chars.find_last_of('a')
find_first_not_of(ch)First different chars.find_first_not_of(' ')
find_last_not_of(ch)Last different chars.find_last_not_of(' ')
compare(str)Compare stringss.compare(t)
at(i)Character with bounds checks.at(3)
front()First characters.front()
back()Last characters.back()
begin()Iterator begins.begin()
end()Iterator ends.end()
rbegin()Reverse begins.rbegin()
rend()Reverse ends.rend()
resize(n)Resize strings.resize(10)
swap(str)Swap stringss.swap(t)
copy()Copy chars to arrays.copy(arr,n)
c_str()Convert to C-strings.c_str()
data()Pointer to characterss.data()
capacity()Current capacitys.capacity()
reserve(n)Reserve memorys.reserve(100)
shrink_to_fit()Reduce capacitys.shrink_to_fit()

c++
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

1

x 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

2

x is a reference, so nums is modified.


Quick Rule

autoauto&
Makes a copyUses the original element (reference)
Original data doesn't changeOriginal data changes
Good for readingGood for modifying or avoiding copies

Remember

  • Read only → auto
  • Modify or avoid copying → auto&

Character Functions (<cctype>)

FunctionPurpose
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>)

FunctionPurpose
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

FunctionPurpose
stoi()String → int
stol()String → long
stoll()String → long long
stof()String → float
stod()String → double
to_string()Number → string

String Stream (<sstream>)

FunctionPurpose
stringstream ss(s)Create stream
getline(ss,word,' ')Read until delimiter
ss >> wordRead word
ss << xWrite to stream

Frequently Used in DSA

FunctionExample
Reverse stringreverse(s.begin(), s.end());
Sort stringsort(s.begin(), s.end());
Count 'a'count(s.begin(), s.end(), 'a');
Lowercasetransform(s.begin(), s.end(), s.begin(), ::tolower);
Uppercasetransform(s.begin(), s.end(), s.begin(), ::toupper);
Palindrome checkreverse(t.begin(), t.end());
Split wordsstringstream ss(s);
Find substrings.find("abc")
Remove substrings.erase(pos, len)
Replace substrings.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

FunctionPurposeExample
size()Lengths.size()
length()Lengths.length()
empty()Check emptys.empty()
clear()Remove alls.clear()
push_back()Add characters.push_back('!')
pop_back()Remove last characters.pop_back()
append()Add strings.append("abc")
+=Add strings += "abc"
+Concatenatea + 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 World

2. Insert, Erase, Replace, Substring

insert()

Adds characters at a particular position.

string s = "hello";

s.insert(2, "ABC");

cout << s;

Output:

heABCllo

Position 2 means insertion happens before index 2.


erase()

Removes characters.

string s = "abcdef";

s.erase(2, 3);

cout << s;

Output:

abf

Meaning:

erase(start, length)
erase(2, 3)

Removes:

c d e

replace()

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:

cdef

Syntax:

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:

6

Important

If not found:

if (s.find("xyz") == string::npos)
    cout << "Not found";

rfind()

Find last occurrence.

string s = "abcabc";

cout << s.rfind("abc");

Output:

3

find_first_of()

Find first character that belongs to a set.

string s = "hello123";

cout << s.find_first_of("0123456789");

Output:

5

First digit is at index 5.


find_last_of()

Find last matching character.

string s = "hello123";

cout << s.find_last_of("0123456789");

Output:

7

find_first_not_of()

Find first character that is not from the given set.

string s = "   hello";

cout << s.find_first_not_of(' ');

Output:

3

Useful 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:

4

4. 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 smaller

Quick rule

compare() == 0  → equal
compare() < 0   → smaller
compare() > 0   → greater

5. Character Access

at()

string s = "hello";

cout << s.at(1);

Output:

e

at() performs bounds checking.


front()

string s = "hello";

cout << s.front();

Output:

h

back()

string s = "hello";

cout << s.back();

Output:

o

6. Iterators

begin() and end()

string s = "abc";

for (auto it = s.begin(); it != s.end(); it++)
    cout << *it;

Output:

abc

rbegin() and rend()

Used for reverse traversal.

string s = "abc";

for (auto it = s.rbegin(); it != s.rend(); it++)
    cout << *it;

Output:

cba

7. Resize and Swap

resize()

string s = "hello";

s.resize(3);

cout << s;

Output:

hel

You can also increase the size:

string s = "abc";

s.resize(5, 'x');

cout << s;

Output:

abcxx

swap()

string a = "hello";
string b = "world";

a.swap(b);

cout << a << " " << b;

Output:

world hello

8. 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:

hello

data()

Access underlying character data.

string s = "hello";

cout << s.data();

Output:

hello

9. copy()

Copies characters into a character array.

string s = "hello";

char arr[10];

s.copy(arr, 3);

arr[3] = '\0';

cout << arr;

Output:

hel

Syntax:

s.copy(array, numberOfCharacters, startPosition);

10. Character Functions <cctype>

Include:

#include <cctype>

tolower()

char ch = 'A';

cout << char(tolower(ch));

Output:

a

toupper()

char ch = 'a';

cout << char(toupper(ch));

Output:

A

isdigit()

Check whether character is a digit.

char ch = '5';

if (isdigit(ch))
    cout << "Digit";

Output:

Digit

isalpha()

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:

olleh

DSA 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:

abcd

Very 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:

3

14. count_if()

Count according to a condition.

string s = "abc123";

int cnt = count_if(s.begin(), s.end(), ::isdigit);

cout << cnt;

Output:

3

15. 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 digits

17. 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 digit

18. none_of()

Check whether none satisfy a condition.

string s = "abc";

if (none_of(s.begin(), s.end(), ::isdigit))
    cout << "No digits";

Output:

No digits

19. transform()

Convert entire string to lowercase.

string s = "HELLO";

transform(s.begin(), s.end(), s.begin(), ::tolower);

cout << s;

Output:

hello

Uppercase:

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:

aabbcca

becomes:

abca

because only consecutive duplicates are removed.


21. rotate()

string s = "abcdef";

rotate(s.begin(), s.begin() + 2, s.end());

cout << s;

Output:

cdefab

22. next_permutation()

string s = "abc";

next_permutation(s.begin(), s.end());

cout << s;

Output:

acb

Useful in permutation problems.


23. prev_permutation()

string s = "cba";

prev_permutation(s.begin(), s.end());

cout << s;

Output:

cab

24. min_element()

string s = "zebra";

auto it = min_element(s.begin(), s.end());

cout << *it;

Output:

a

25. max_element()

string s = "zebra";

auto it = max_element(s.begin(), s.end());

cout << *it;

Output:

z

26. String Conversion Functions

Include:

#include <string>

stoi() — String → int

string s = "123";

int x = stoi(s);

cout << x + 10;

Output:

133

stol() — 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
mango

Very 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:

cat

Because x is a copy.

auto& → Original

vector<string> v = {"cat", "dog"};

for (auto &x : v) {
    x = "hello";
}

cout << v[0];

Output:

hello

Because x refers to the original element.

Easy rule

auto   → copy
auto&  → original

For 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:

FunctionDSA 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
stringstreamSplit/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.

Comments (2)