Codiqo

Learn C++ · lesson 7 of 61 · about 7 minutes

String Methods

A scroll says where the treasure is. Cut, search and change text with substr, find and replace.

What you'll learn

  • Cut text with substr
  • Search with find
  • Change text with replace and insert

A secret scroll

Your hero finds a scroll: *The treasure is in the east tower*. The game should pull out just the place, *east tower*. To do that it has to find where the place starts, then cut out everything after it.

The string toolkit

| Method | Does |
|---|---|
| s.substr(pos, len) | copies len characters starting at pos (leave len out to go to the end) |
| s.find(text) | the position of the first match, or std::string::npos |
| s.replace(pos, len, text) | swaps a section for new text |
| s.insert(pos, text) | adds text at a position |
| s.empty() | true if there are no characters |

Find where the place starts, then cut it out

#include <iostream>
#include <string>

int main() {
    std::string scroll = "The treasure is in the east tower";
    std::size_t at = scroll.find("in the ");
    std::cout << at << "\n";
    std::cout << scroll.substr(at + 7) << "\n";
    std::cout << scroll.substr(4, 8) << "\n";
}

Output

16
east tower
treasure

Not found

When find can't find the text, it returns a special value, std::string::npos. Check for it before you use the position for anything.

Replacing text, and checking for npos

#include <iostream>
#include <string>

int main() {
    std::string sign = "Beware of the troll";
    sign.replace(sign.find("troll"), 5, "dragon");
    std::cout << sign << "\n";
    if (sign.find("troll") == std::string::npos) {
        std::cout << "No troll here\n";
    }
}

Output

Beware of the dragon
No troll here

Tip

Asking substr to start past the end of a string doesn't quietly give nothing: the program stops with std::out_of_range.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.