C++ String Manipulation Functions Explained

Formulas & functions · Updated November 23, 2026

The most common string manipulation functions in C++ come from the std::string class (in <string>) and include length(), substr(), find(), replace(), append(), insert(), erase(), and compare(). These cover the vast majority of everyday tasks like getting a substring, searching for text, modifying content, and comparing strings, and they work safely with dynamic memory management.

Background: From C-Strings to std::string

Before C++ had a standard string class, programmers used C-style strings: null-terminated arrays of char (e.g., char name[] = "Alice";). These required manual memory management, careful bounds checking, and functions like strlen(), strcpy(), and strcat() from <cstring>. Mistakes were common—buffer overflows, forgotten null terminators, and accidental writes past array ends.

C++ introduced std::string in the standard library to encapsulate this complexity. It manages its own memory, grows automatically, and provides member functions that are safer and more intuitive. Since C++11, the class uses move semantics for efficient passing, and modern C++ (C++17, C++20) added even more capabilities like string_view for non-owning references and starts_with()/ends_with() checks.

Core Functions: What Each One Does

Here are the essential member functions with brief examples. Assume std::string s = "Hello World"; unless noted.

  • length() / size() – Returns the number of characters (excluding null terminator). Example: s.length() returns 11.
  • substr(pos, count) – Extracts a substring starting at pos for count characters. Example: s.substr(6, 5) returns "World". If count is omitted, it goes to the end.
  • find(str, pos) – Searches for the first occurrence of str starting at pos (default 0). Returns the index or std::string::npos if not found. Example: s.find("o") returns 4.
  • rfind(str, pos) – Searches backward from pos (default end). Example: s.rfind("o") returns 7.
  • replace(pos, count, str) – Replaces count characters starting at pos with str. Example: s.replace(0, 5, "Goodbye") results in "Goodbye World".
  • append(str) or += – Adds characters to the end. Example: s.append("!") gives "Hello World!".
  • insert(pos, str) – Inserts str at index pos. Example: s.insert(5, ",") gives "Hello, World".
  • erase(pos, count) – Removes count characters starting at pos. Example: s.erase(5, 1) gives "HelloWorld".
  • compare(str) – Lexicographically compares with another string. Returns 0 if equal, negative if less, positive if greater. Example: s.compare("Hello") returns a positive value.
  • c_str() – Returns a C-style null-terminated const char* for interfacing with legacy C functions. Example: printf("%s", s.c_str());

How It Works: Indexing, npos, and Mutability

Strings are zero-indexed: the first character is at position 0. The find() family returns std::string::npos when no match exists—this is a special constant equal to the largest possible size_t value (typically 18446744073709551615 on 64-bit). Always compare against npos explicitly, never assume a negative return (since size_t is unsigned).

Most functions are mutating—they change the string in place. For example, replace() modifies the original object. If you need a copy, assign to a new variable first: std::string modified = s; then call modified.replace(...). The class also supports direct indexing with s[i] (no bounds check) and s.at(i) (throws std::out_of_range if out of bounds).

Memory reallocation happens automatically when the string grows. To avoid repeated reallocations when building a large string, use reserve(n) to preallocate capacity.

Choosing the Right Function: A Decision Guide

Different tasks call for different functions. Here’s a quick mental map:

  • Get a piece of text: substr().
  • Check if a substring exists: find() != npos.
  • Find all occurrences: loop with find() and update the start position to found + 1.
  • Replace all occurrences: no single function—write a loop using find() and replace(), or use std::regex for complex patterns.
  • Compare ignoring case: convert both to lowercase with std::tolower in a loop, or use std::strcasecmp on C-strings (non-standard but common).
  • Split by delimiter: use std::getline with a std::stringstream, or write a loop with find() and substr().
  • Trim whitespace: use find_first_not_of() and find_last_not_of() with substr().

For performance-critical code, prefer string_view (C++17) to avoid copies when passing read-only strings to functions.

Common Problems and Pitfalls

Even with std::string, several mistakes recur:

  • Off-by-one errors with substr(): The second parameter is a count, not an end index. s.substr(0, 5) gives characters 0–4, not 0–5.
  • Forgetting npos: Using if (s.find("x")) is wrong because find returns 0 if found at the start (which is false in a boolean context). Always compare to npos.
  • Assuming replace() replaces all occurrences: It only replaces one segment. For global replacement, you need a loop.
  • Mixing std::string and C-strings: Implicit conversion works, but be careful with c_str()—it returns a pointer that becomes invalid if the string is modified or destroyed. Don’t store it long-term.
  • Index out of range with operator[]: No exception is thrown; it’s undefined behavior. Use at() if you need safety.

Performance and Efficiency Considerations

String operations are not free. substr() allocates a new string (O(n) time and memory). find() is typically O(n*m) in the worst case for naive search, though most implementations use efficient algorithms like Boyer-Moore or Two-Way. replace() may shift characters, also O(n).

To minimize overhead:

  • Use reserve() when building strings incrementally.
  • Pass strings by const std::string& or std::string_view to avoid copies.
  • For repeated concatenation, prefer += over s = s + x because the latter creates a temporary.
  • If you need to search many patterns, consider std::regex (slower but more powerful) or a proper trie structure.

Modern compilers with optimization flags often inline small string operations, and the short-string optimization (SSO) means strings up to ~15 characters (implementation-defined) avoid heap allocation entirely.

Alternatives: std::string_view, Regex, and Third-Party

For read-only operations, std::string_view (C++17) provides a lightweight reference to a character sequence without owning it. It supports substr(), find(), and comparison, but not mutation. This is ideal for function parameters.

For complex pattern matching, std::regex (in <regex>) offers Perl-like syntax. Example: std::regex re("\\d+"); matches digits. However, regex is notoriously slow; for simple splits or replacements, manual loops are faster.

Third-party libraries like Boost.StringAlgo (now largely incorporated into C++17/20) provide boost::algorithm::split, to_upper, and trim. These are convenient but add a dependency.

Frequently Asked Questions

How do I convert a string to an integer?
Use std::stoi(s) (or stol, stoll for larger types). It throws std::invalid_argument if no conversion is possible and std::out_of_range if the value overflows. For floating-point, use std::stof or std::stod. Example: int n = std::stoi("42"); yields 42.

Why does find() return a huge number when not found?
Because it returns std::string::npos, which is the maximum value of size_t. This is a sentinel value, not a valid index. Always check if (pos != std::string::npos).

Can I modify a character in a string?
Yes. Use s[i] = 'x' or s.at(i) = 'x'. The latter throws an exception if i is out of bounds. Strings are mutable, unlike std::string_view.

What’s the difference between size() and capacity()?
size() is the number of characters currently in the string. capacity() is the amount of allocated memory, which is always >= size. You can reduce capacity with shrink_to_fit() (non-binding) or increase it with reserve().

How do I split a string by a delimiter?
The simplest way: use std::stringstream and std::getline. For example: std::stringstream ss("a,b,c"); std::string token; while (std::getline(ss, token, ',')) { ... }. This splits on commas. For multiple delimiters, you’d need a custom loop.

Is std::string thread-safe?
No. Different strings can be used in different threads safely, but a single string object cannot be modified concurrently without external synchronization (e.g., a mutex). Read-only concurrent access is safe.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.