The C++ Standard Template Library (STL) provides a rich set of string functions through the std::string class, covering construction, modification, inspection, searching, and conversion. These functions are part of the <string> header and operate on dynamic character arrays, offering safe and convenient alternatives to C-style strings.
Background: From C Strings to std::string
Before the STL, C programmers used null-terminated character arrays (char[]) with functions like strlen(), strcpy(), and strcat(). These were error-prone: you had to manually manage memory, avoid buffer overflows, and remember to include the terminating null character. std::string was introduced in the C++ standard library to encapsulate these operations, automatically managing memory and providing a consistent interface. It first appeared in the 1998 C++ standard and has been extended since (e.g., C++11 added shrink_to_fit(), C++17 added data() returning non-const pointer, C++20 added starts_with() and ends_with()). The class is defined in the <string> header, and it is actually a typedef for std::basic_string<char>, which can be instantiated for other character types like wchar_t (wide strings) or char8_t (UTF-8).
Core Functions: Construction and Assignment
You can create strings in several ways, and assign or append to them using operators or member functions.
- Constructors:
std::string s;(empty),std::string s("hello");(from C-string),std::string s(10, 'x');(10 copies of ‘x’),std::string s(other);(copy constructor). - Assignment:
s = "new";ors.assign("new");– both replace the current content. - Appending:
s += " world";ors.append(" world");– adds to the end. There is alsopush_back(char)to add a single character. - Insertion:
s.insert(pos, str);inserts a string at a given index (0-based). - Erasing:
s.erase(pos, len);removeslencharacters starting atpos. - Clearing:
s.clear();removes all characters, leaving an empty string (size 0).
Example: std::string s = "Hello"; s += " World"; results in "Hello World".
Inspection and Access: Size, Length, and Characters
To read or check the contents of a string, you have several functions:
size()andlength()– both return the number of characters (they are synonyms). Useempty()to check if size is zero.operator[]andat()– access a character at a given index.at()performs bounds checking and throwsstd::out_of_rangeif the index is invalid, whileoperator[]does not (undefined behavior if out of bounds).front()andback()– return the first and last character, respectively (C++11 onward).c_str()anddata()– return a pointer to a null-terminated character array.data()since C++11 also guarantees null-termination; before that it was not guaranteed.substr(pos, len)– returns a new string that is a substring starting atposof lengthlen. Iflenis omitted, it takes the rest of the string.
Search and Comparison Functions
Finding characters or substrings is a common task. The main search functions are:
find(str, pos)– returns the index of the first occurrence ofstrstarting frompos(default 0). Returnsstd::string::nposif not found.rfind(str, pos)– searches backward frompos(default end) for the last occurrence.find_first_of(str, pos)– finds the first character that matches any character instr.find_last_of(str, pos)– finds the last character that matches any character instr.find_first_not_of(str, pos)– finds the first character that is not instr.find_last_not_of(str, pos)– finds the last character that is not instr.compare(str)– compares lexicographically; returns 0 if equal, negative if less, positive if greater. You can also use operators==,!=,<, etc., which are more readable.
Example: std::string s = "Hello World"; size_t pos = s.find("World"); yields pos == 6. If not found, pos == std::string::npos (which is static_cast<size_t>(-1)).
Modification and Conversion Functions
Beyond basic editing, there are functions to change the string’s contents or convert to other types.
replace(pos, len, str)– replaces a substring withstr.swap(other)– exchanges contents with another string efficiently (constant time).resize(n)– changes the length; if shorter, characters are truncated; if longer, new characters are default-initialized (or you can specify a fill character).reserve(n)– pre-allocates memory for at leastncharacters to avoid reallocations during repeated appends.shrink_to_fit()– requests the capacity to be reduced to fit the size (non-binding, implementation may ignore).- Numeric conversions (C++11):
stoi(),stol(),stoll(),stof(),stod(), etc., convert a string to integer or floating-point types. Example:int n = std::stoi("42"); - To convert numbers to string, use
std::to_string()(C++11). Example:std::string s = std::to_string(3.14);yields"3.140000". - Character classification:
std::isalpha(),std::isdigit(), etc., are in<cctype>and work on individual characters, not directly on strings.
Common Problems and How to Avoid Them
Even with std::string, there are pitfalls:
- Using
nposincorrectly: Always checkif (s.find(...) != std::string::npos)before using the index. Forgetting this leads to using a huge number as an index. - Out-of-bounds access: Prefer
at()overoperator[]when you are not sure the index is valid, to catch errors with exceptions. - Modifying while iterating: If you call functions like
insert()orerase()inside a loop that uses indices, the indices shift. Use iterators carefully or recompute indices. - Performance with many concatenations: Repeated
+=can cause multiple reallocations. Usereserve()beforehand or usestd::ostringstreamfor complex formatting. - Confusing
size()withcapacity():size()is the number of characters,capacity()is the allocated memory size. They differ afterreserve(). - Null characters in strings:
std::stringcan contain embedded null characters, butc_str()returns a C-string that stops at the first null. Usedata()andsize()together for binary data.
Alternatives and Related Facilities
While std::string is the primary class, there are alternatives depending on the need:
std::string_view(C++17): A non-owning view of a string. Use it for function parameters to avoid copying when you only need to read the string. It does not allocate memory and cannot modify the underlying data.- Character arrays (
char[]): Still used for low-level or performance-critical code, but you must manage memory manually. std::wstring: For wide characters (e.g., Unicode on Windows). Similar functions but withwchar_t.- Regular expressions (
std::regex): For pattern matching, not just simple search. More powerful but slower. std::ostringstream: For formatted output (likeprintfbut type-safe). Good for building strings with mixed types.
Frequently Asked Questions
What is the difference between size() and length()?
There is no difference. Both return the number of characters in the string. length() is kept for compatibility with C-style string functions, while size() is consistent with other STL containers like std::vector.
How do I convert a string to an integer?
Use std::stoi() (string to int). For example: int x = std::stoi("123"); It throws std::invalid_argument if no conversion could be performed, and std::out_of_range if the value is out of range. For long or long long, use stol() or stoll().
Why does find() return npos and how do I check it?
npos is a special constant (usually the maximum value of size_t) that indicates “not found”. Always compare the return value with std::string::npos to check if a substring exists. For example: if (s.find("needle") != std::string::npos) { /* found */ }.
Can I use std::string with binary data?
Yes, because std::string can hold null characters. Use the constructor that takes a pointer and length: std::string s(data, len). When accessing the data, use data() and size() instead of c_str() (which truncates at the first null).
How do I split a string by a delimiter?
There is no built-in split() function in the STL. A common approach is to use find() and substr() in a loop. For example, to split on commas:
std::vector<std::string> parts;
size_t start = 0, end = 0;
while ((end = s.find(',', start)) != std::string::npos) {
parts.push_back(s.substr(start, end - start));
start = end + 1;
}
parts.push_back(s.substr(start));
Alternatively, use std::getline() with a string stream for line-based splitting.
Related
- BigQuery SELECT from Multiple Tables: 4 Ways
- Traffic Light PLC Program: How It Works
- DB10DL 10.8V Lithium Ion Micro Driver Drill Guide
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- How to Expand Filter Range in ExcelTo expand an Excel filter, include the added rows or columns in the filter’s source range, then apply…
- Excel Formula for Grouping Data by CategoryIn Excel for Microsoft 365, use UNIQUE to list each category once and FILTER to return the records…
- NPV vs PV in Excel: Formulas and Key Differences ExplainedIn Excel, use NPV to discount a series of periodic cash flows, but keep a time-zero investment outside…
- How to Paste in Excel When a Filter Is Applied SafelyTo paste into a filtered Excel list without changing hidden rows, select the destination cells, choose Home >…
- Oracle SQL Left String Function: Use SUBSTR InsteadOracle SQL does not provide a built-in LEFT() string function. To return the first characters of a value,…
- Excel SUM Function: Does It Count Filtered Values?Yes. In Excel for Microsoft 365, SUM adds every numeric value in its referenced range, including values in…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.