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 atposforcountcharacters. Example:s.substr(6, 5)returns"World". Ifcountis omitted, it goes to the end.find(str, pos)– Searches for the first occurrence ofstrstarting atpos(default 0). Returns the index orstd::string::nposif not found. Example:s.find("o")returns 4.rfind(str, pos)– Searches backward frompos(default end). Example:s.rfind("o")returns 7.replace(pos, count, str)– Replacescountcharacters starting atposwithstr. 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)– Insertsstrat indexpos. Example:s.insert(5, ",")gives"Hello, World".erase(pos, count)– Removescountcharacters starting atpos. 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-terminatedconst 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 tofound + 1. - Replace all occurrences: no single function—write a loop using
find()andreplace(), or usestd::regexfor complex patterns. - Compare ignoring case: convert both to lowercase with
std::tolowerin a loop, or usestd::strcasecmpon C-strings (non-standard but common). - Split by delimiter: use
std::getlinewith astd::stringstream, or write a loop withfind()andsubstr(). - Trim whitespace: use
find_first_not_of()andfind_last_not_of()withsubstr().
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: Usingif (s.find("x"))is wrong becausefindreturns 0 if found at the start (which is false in a boolean context). Always compare tonpos. - Assuming
replace()replaces all occurrences: It only replaces one segment. For global replacement, you need a loop. - Mixing
std::stringand C-strings: Implicit conversion works, but be careful withc_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. Useat()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&orstd::string_viewto avoid copies. - For repeated concatenation, prefer
+=overs = s + xbecause 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
- Shortcut to Switch Between Windows (All OS)
- Generate Random Number HTML: JS & Math.random Code
- Google Sheets Percentage Increase Formula
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Random QR Code: What Happens If You Scan One?A random QR code is simply a QR code you encounter without knowing its origin, purpose, or destination.…
- Excel Rank by Number: Formulas and Tie HandlingTo rank numbers in Excel, use RANK.EQ. With the value to rank in B2 and comparison values in…
- Formula subtotal po polsku? Excel SUBTOTAL ExplainedFunkcja SUBTOTAL w polskiej wersji Excel nosi nazwę SUMY.CZĘŚCIOWE. Aby ją wpisać, używasz formuły =SUMY.CZĘŚCIOWE(1;A2:A10) – gdzie pierwszy…
- How to Sum and Round in Excel in One FormulaTo add values and round the final total in one step, use =ROUND(SUM(B2:B5),2). This example assumes the numbers…
- COUNTIF Excel Text in Cell: Exact or Partial MatchesTo count cells that contain particular text anywhere in their contents, use =COUNTIF(A2:A100,"*apple*"); the asterisks allow any characters…
- Arduino String Functions: Methods, Examples, and TipsArduino String functions are methods and operators for storing, joining, searching, editing, and converting text in an Arduino…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.