C++’s built-in string functions are the member functions of the std::string class (and the older char* C-string functions in <cstring>). The most useful ones include length(), substr(), find(), append(), replace(), and compare() — all part of the Standard Library.
Background: std::string vs C-strings
Before C++ had std::string, programmers used C-style strings: arrays of char terminated by a null character ('\0'). Those require functions like strlen(), strcpy(), and strcat() from <cstring>. Since C++98, the std::string class has provided a safer, more intuitive interface. It manages memory automatically, knows its own length, and supports operators like + and ==. For modern C++ (C++11 and later), you should almost always prefer std::string over raw C-strings.
Essential std::string Member Functions
Here are the most commonly used member functions, grouped by what they do:
- Size and capacity:
size(),length(),empty(),capacity(),reserve(),shrink_to_fit() - Element access:
operator[],at(),front(),back() - Modification:
append(),push_back(),pop_back(),insert(),erase(),clear(),replace(),swap() - Searching:
find(),rfind(),find_first_of(),find_last_of(),find_first_not_of(),find_last_not_of() - Comparison:
compare() - Substrings and conversion:
substr(),c_str(),data()
How They Work: Key Examples
Let’s look at concrete examples you can compile and run.
#include <iostream>
#include <string>
int main() {
std::string s = "Hello, world!";
// length() returns the number of characters (13)
std::cout << s.length() << '\n';
// substr(pos, len) extracts a substring
std::string sub = s.substr(7, 5); // "world"
std::cout << sub << '\n';
// find() returns the index of the first occurrence, or npos
size_t pos = s.find("world"); // 7
if (pos != std::string::npos) {
std::cout << "Found at " << pos << '\n';
}
// append() adds to the end
s.append(" How are you?");
std::cout << s << '\n';
// replace(start, count, new_str)
s.replace(0, 5, "Hi"); // "Hi, world! How are you?"
std::cout << s << '\n';
// compare() returns 0 if equal, negative if less, positive if greater
std::string a = "apple";
std::string b = "banana";
int cmp = a.compare(b); // negative because 'a' < 'b'
std::cout << cmp << '\n';
return 0;
}
Note that find() returns std::string::npos (a special constant) when the substring is not found. Always check against npos, not -1.
Choosing the Right Function
Picking the right function depends on what you need:
- Need to check if a string is empty? Use
empty()— it’s faster than comparingsize() == 0. - Need to get a substring? Use
substr()— it returns a new string. - Need to search for a character or substring? Use
find()for forward search,rfind()for backward. - Need to modify a portion? Use
replace()orerase(). - Need to compare ignoring case?
std::stringdoesn’t have a built-in case-insensitive compare; you’d need to convert to lowercase first or use a custom loop.
Common Pitfalls and Misconceptions
One frequent mistake is confusing size() with capacity(). size() is the number of characters currently in the string; capacity() is how many characters the string can hold before reallocating. They are often different.
Another pitfall: using c_str() and then modifying the string. The pointer returned by c_str() is invalidated if the string is modified. Also, c_str() returns a const char*, so you can’t modify the string through it.
Misconception: std::string is always null-terminated. In C++11 and later, data() and c_str() are guaranteed to be null-terminated, but the internal buffer may not have a null at the end until you call one of those. Don’t rely on the internal representation.
Performance and Efficiency
String operations have different costs. length() is O(1) — it just reads a stored size. find() is O(n*m) in the worst case (n = string length, m = pattern length), but typical implementations are faster. substr() copies characters, so it’s O(k) where k is the substring length. append() can be amortized O(1) if the capacity is sufficient; otherwise it reallocates and copies the entire string.
If you do many concatenations, consider using reserve() to preallocate capacity, or use std::ostringstream for complex formatting.
Alternatives and Related Tools
For more advanced string manipulation, C++17 introduced std::string_view — a non-owning view of a string that avoids copies. C++20 added std::format for safe, readable formatting. For regular expressions, use std::regex (though it can be slow). For character-by-character processing, you can use iterators or range-based for loops.
If you need to work with C libraries, you’ll often use c_str() to get a null-terminated const char*. But be careful: the pointer is only valid until the string is modified or destroyed.
Frequently Asked Questions
What’s the difference between size() and length()? They are identical — both return the number of characters in the string. length() is more natural for strings, while size() is used in containers like vector.
How do I convert a string to an integer? Use std::stoi() (since C++11) which throws std::invalid_argument if the conversion fails. For example: int n = std::stoi("123");. For C compatibility, you can use atoi(), but it doesn’t report errors.
Why does find() return npos instead of -1? npos is a static constant defined as size_t(-1), which is the largest possible size_t value. It’s used because the return type is size_t (unsigned), so -1 is not representable.
How do I split a string by a delimiter? There’s no built-in split function, but you can use a loop with find() and substr(), or use std::getline() with a stringstream. For example:
std::stringstream ss("a,b,c");
std::string token;
while (std::getline(ss, token, ',')) {
std::cout << token << '\n';
}
Is std::string thread-safe? Different std::string objects are safe to use in different threads concurrently. However, if multiple threads access the same std::string object without synchronization, that’s a data race and undefined behavior.
Can I use std::string with Unicode? std::string stores bytes, not characters. For UTF-8 encoded text, you can store the bytes in a std::string, but operations like length() will return the byte count, not the number of Unicode characters. For proper Unicode handling, consider std::wstring (though platform-dependent) or a library like ICU.
Related
- Number 5 Blue Balloon Meaning & Origins
- SQL Count Duplicates: Find and Group Them
- Shortcut to Duplicate Tab: All Browsers
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Formula for Time Clock Hours In and Out by ShiftFor clock-in time in A2 and clock-out time in B2, enter =MOD(B2-A2,1)*24 to return the shift length as…
- SQL Split String by Delimiter: Functions by DatabaseThere is no single SQL function for splitting a string by a delimiter across all databases. Use STRING_SPLIT…
- Databricks SQL Window Functions: Syntax and ExamplesDatabricks SQL window functions calculate a value across related rows while keeping each input row in the result.…
- DATEDIF in Excel: Examples for Years, Months, and DaysTo calculate the time between two dates in Excel, use DATEDIF. With a start date in A2 and…
- Excel INDIRECT Errors: Causes, Fixes, and ExamplesAn Excel INDIRECT error usually means the text supplied to INDIRECT cannot be turned into a valid cell…
- Filter an Excel Column Based on a List of ValuesTo filter a column in Excel for Microsoft 365 on Windows, select your data, choose Data > Filter,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.