C++ ยท Chapter 12 of 49

C++ String Functions

The std::string class provides useful member functions such as `.length()`, `.substr()`, `.find()`, and `.append()`. These let you inspect and transform text without manual loops.

For case conversion or trimming, you'll often combine `<algorithm>` with a lambda, since std::string itself doesn't have built-in upper/lower methods.

Common methods

`.length()`/`.size()` return character count, `.substr(pos, len)` extracts a piece, `.find(str)` returns the index of the first match or `std::string::npos` if not found.

Modifying strings

`.append()` or `+=` add text to the end; `.replace()` swaps a range for new text; `.erase()` removes characters.

Example 1 (cpp)
std::string s = "Hello World";
std::cout << s.substr(6, 5);
Output
World

substr(6, 5) extracts 5 characters starting at index 6.

Example 2 (cpp)
std::string s = "Hello";
if (s.find("ell") != std::string::npos)
    std::cout << "found";
Output
found

find() returns npos if the substring isn't present.

Key points

  • length()/size() return the character count.
  • substr(pos, len) extracts a substring.
  • find() returns std::string::npos if not found.
  • append(), replace(), erase() modify strings.
๐Ÿ’ก Note: Always compare find()'s result against std::string::npos, not -1, for correctness.

๐Ÿ“ Quick Quiz

1. What does s.substr(0, 3) do?

2. What does find() return if the text isn't present?

3. Which function returns the number of characters?