Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 171 ยท Strings

String Methods

A practical guide to C++ std::string methods: find and rfind, npos, substr, replace, insert, erase, append, starts_with, ends_with, contains, resize and c_str.

Creating and joining strings is only the start. Real programs search text, cut pieces out of it, replace words, strip whitespace and check prefixes. std::string has member functions for all of this, and once you know a dozen of them you can handle most text-processing tasks without reaching for a library.

This lesson tours the methods you'll use most, grouped by job: searching (find, rfind, find_first_of and the magic value npos), testing (starts_with, ends_with, and C++23's contains), extracting (substr), modifying (append, insert, erase, replace), sizing (resize, reserve) and handing text to C code (c_str). Along the way you'll build small, reusable helpers: find all matches, replace all, split a key-value pair and trim whitespace.

Quick reference

Method What it does Returns
find(x, pos = 0) first occurrence of x at or after pos index or npos
rfind(x, pos = npos) last occurrence of x starting at or before pos index or npos
find_first_of(chars) / find_last_of(chars) first / last character that is any of chars index or npos
find_first_not_of(chars) / find_last_not_of(chars) first / last character not in chars index or npos
starts_with(x) / ends_with(x) prefix / suffix test (C++20) bool
contains(x) does x occur anywhere? (C++23) bool
substr(pos, count = npos) copy of a piece new std::string
append(x) / push_back(c) add to the end the string / nothing
insert(pos, x) insert before index pos the string
erase(pos, count = npos) / pop_back() remove characters the string / nothing
replace(pos, count, x) replace a range with x the string
clear() remove everything nothing
resize(n, c = '\0') / reserve(n) change size / pre-allocate capacity nothing
c_str() / data() pointer to null-terminated characters const char* / char*

Wherever x appears, you can pass a std::string, a string literal, a std::string_view or (for most methods) a single char. Positions are zero-based indexes of type std::size_t.

Searching: find, rfind and npos

s.find(x) returns the index where x first starts. If x isn't there, it returns the special value std::string::npos, the largest possible std::size_t value. The name means "no position".

That return convention leads to the single most common string bug in C++:

C++
if (text.find("error")) { ... }                       // WRONG
if (text.find("error") != std::string::npos) { ... }  // right

The first line is wrong twice: a match at index 0 converts to false, and "not found" (npos, a huge non-zero number) converts to true. Always compare with npos, or, if you only need a yes/no answer, use contains (next section).

Both find and rfind accept a starting position. That makes it easy to find every occurrence: search again from just past the previous match.

C++ Finding text with find and rfind

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Store the result of find in a std::size_t (or auto), never in an int or unsigned int. npos doesn't fit in either: in an unsigned int it becomes 4294967295 on our server, so a later pos == std::string::npos test is false even though nothing was found.

The find_first_of family works on sets of characters, not substrings. find_first_of("aeiou") finds the first vowel. The _not_of versions find the first character outside the set, which is exactly what you need to skip whitespace, as the trim helper below shows.

Testing: starts_with, ends_with and contains

For yes/no questions, three methods say what you mean directly:

  • s.starts_with(x) and s.ends_with(x) (C++20) test a prefix or suffix.
  • s.contains(x) (C++23) tests whether x occurs anywhere. It's a clearer spelling of s.find(x) != std::string::npos.

All three accept a string, a literal, a string_view or a single char, and they're case-sensitive.

C++ starts_with, ends_with and contains

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

"photo.JPG".ends_with(".jpg") would be false because of the case difference. To compare case-insensitively, convert a copy to lowercase first, using the std::tolower loop from Strings with std::string.

Extracting: substr

s.substr(pos, count) returns a new string containing count characters starting at index pos. Leave out count to take everything up to the end. If count runs past the end, it's simply clamped, but if pos is greater than s.size(), substr throws std::out_of_range.

find and substr together are the classic way to split text at a separator:

C++ Splitting text with find and substr

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Every call to substr allocates and copies characters, which is fine for short text but adds up in hot loops over large inputs. std::string_view gives you a non-copying alternative whose substr just points into the original string.

Modifying: append, insert, erase and replace

These methods change the string in place. Except for push_back and pop_back, they return a reference to the string itself, so calls can be chained.

  • append(x) adds to the end, like +=. It also has a count form: append(3, '!') adds three exclamation marks.
  • push_back(c) adds one character; pop_back() removes the last one (on an empty string, that's undefined behavior).
  • insert(pos, x) inserts x before index pos. insert(s.size(), x) appends.
  • erase(pos, count) removes count characters starting at pos. erase(pos) removes everything from pos to the end.
  • replace(pos, count, x) removes count characters at pos and puts x in their place. x can be shorter or longer.
  • clear() makes the string empty.
C++ append, insert, erase and replace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The phone example chains two replace calls. It's safe here only because C++17 evaluates a.b(...) left to right: the first replace finishes before the second phone.find(' ') runs. For anything longer, separate statements are easier to follow.

To delete every occurrence of a character, you don't need a loop: C++20 added the free functions std::erase(s, ' ') and std::erase_if(s, predicate), which work on strings and on most containers. For example, std::erase_if(s, [](unsigned char c) { return std::isspace(c); }) removes all whitespace. You'll learn the []( ) { } lambda syntax in Lambda Expressions.

Two helpers every project needs: replace_all and trim

std::string::replace changes one range. Replacing every occurrence of a word is a short loop: find, replace, and continue searching after the inserted text, so a replacement that contains the search word doesn't cause an endless loop. Trimming whitespace from both ends combines find_first_not_of and find_last_not_of.

C++ replace_all and trim

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Notice that replace_all takes the text by non-const reference (std::string&) because it modifies the caller's string, while trim takes a const std::string& and returns a new string. Parameters: by Value, by Reference and by const Reference explains when to choose which.

Size and capacity: resize, reserve and capacity

A string's size is how many characters it holds; its capacity is how many it can hold before it must allocate more memory.

  • resize(n) changes the size. Growing pads with '\0' characters, or with a character you choose: resize(10, '.'). Shrinking cuts characters off the end.
  • reserve(n) sets aside capacity for at least n characters without changing the size. When you know roughly how long a string will become, reserving first avoids repeated reallocations while you append.
  • capacity() reports the current capacity. The exact numbers are implementation details.

Talking to C: c_str and data

Many C libraries and operating-system functions expect a const char* pointing to null-terminated text. s.c_str() gives you exactly that, and s.data() does the same (since C++17 it returns a non-const char* on a non-const string, so C functions can write into an existing buffer).

C++ resize, reserve and c_str

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The pointer from c_str() or data() belongs to the string. It becomes invalid as soon as the string is modified in a way that might reallocate, or when the string is destroyed. Use it right away, and never keep it longer than the string. Calling c_str() on a temporary such as (a + b).c_str() and storing the pointer is a classic dangling-pointer bug; C-Style Strings and Character Arrays covers the C side in depth.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. With std::string s = "error: disk full";, why is if (s.find("error")) wrong?

    find returns an index. Compare it with std::string::npos, or use s.contains("error") (C++23) or s.starts_with("error") (C++20).
  2. 2. What does std::string("2026-10-17").substr(5, 2) return?

    substr(pos, count) copies count characters starting at index pos. Index 5 is '1', so the result is "10".
  3. 3. What is s after std::string s = "abcdef"; s.erase(1, 3);?

    erase(1, 3) removes three characters starting at index 1, which are b, c and d, leaving "aef".
  4. 4. In a replace-all loop, why does the next search start at pos + to.size()?

    Replacing "-" with "--" and searching again from pos would find the new "-" endlessly. Skipping the replacement avoids that.
  5. 5. Which call tells you whether a file name has the extension .csv?

    ends_with (C++20) tests the suffix directly. The find comparison would test for a prefix, and the rfind one checks that .csv does NOT occur.

Summary

  • find, rfind and the find_first_of / find_last_not_of family return an index or std::string::npos. Always compare with npos, and store results in std::size_t.
  • starts_with, ends_with (C++20) and contains (C++23) answer yes/no questions directly.
  • substr(pos, count) copies a piece; it clamps count but throws if pos is past the end.
  • append, push_back, insert, erase, pop_back, replace and clear modify the string in place; most return the string so calls can chain.
  • Build helpers like replace_all (continue after the replacement) and trim (find_first_not_of + find_last_not_of); C++20's std::erase and std::erase_if remove characters without loops.
  • resize changes the size, reserve pre-allocates capacity, and c_str()/data() give C code a null-terminated pointer that's only valid while the string is unchanged.

Next: std::string_view, which lets you look at text without copying it.