There is no single built-in function named “string” in C++; instead, the C++ Standard Library provides a rich set of member functions and free functions for the std::string class (defined in <string>). These cover construction, capacity, element access, modification, searching, comparison, and conversion. This article lists the most commonly used ones with concrete examples, and explains how to choose between them.
Background: What std::string Actually Is
In C++, std::string is a class template specialization that manages a dynamic array of characters. It was introduced in the C++ standard library (originally from the STL) and is part of the std namespace. Unlike C-style strings (null-terminated char arrays), std::string stores its length separately, so it can contain embedded null characters and does not require manual memory management. The class provides overloaded operators like + for concatenation and == for comparison, which are not available for raw arrays.
How String Functions Work: Member vs. Free Functions
String operations come in two forms. Member functions are called on a string object, e.g., s.size(). Free functions take strings as arguments, e.g., std::stoi(s) or std::getline(is, s). The member functions are further divided into categories:
- Capacity:
size(),length(),max_size(),resize(),capacity(),reserve(),shrink_to_fit(),clear(),empty() - Element access:
operator[],at(),front(),back(),data(),c_str() - Modifiers:
append(),push_back(),pop_back(),insert(),erase(),replace(),swap(),assign(),operator+= - Search:
find(),rfind(),find_first_of(),find_last_of(),find_first_not_of(),find_last_not_of() - Comparison:
compare(), overloaded==,!=,<, etc. - Conversion:
c_str(),data(),stoi(),stol(),stod(),to_string()
Free functions include std::getline, std::stoi family, std::to_string, and std::swap (which works for strings).
Common Operations with Examples
Here are the most frequently used string functions with minimal code snippets:
- Length and emptiness:
s.size()returns the number of characters;s.empty()returns true if size is 0. - Concatenation: Use
s1 + s2ors1.append(s2). Example:std::string a = "Hello"; a += " World";results in"Hello World". - Find a substring:
s.find("World")returns the index of the first occurrence, orstd::string::nposif not found. Example:std::string s = "Hello World"; size_t pos = s.find("World"); // pos == 6 - Extract a substring:
s.substr(pos, len)returns a new string. Example:s.substr(6, 5)gives"World". - Replace a part:
s.replace(pos, len, newStr). Example:s.replace(6, 5, "C++");makes"Hello C++". - Convert to number:
int n = std::stoi("123");gives 123. For floating point, usestd::stod. - Convert from number:
std::string s = std::to_string(3.14);gives"3.140000"(default formatting).
How to Choose the Right Function
Choosing depends on the task:
- Need length? Use
size()(same aslength(); both return the same value). - Need to check if a string contains another? Use
find()and compare tonpos. - Need to modify in place? Use
insert(),erase(),replace(). - Need to compare ignoring case? There is no built-in case-insensitive compare; you must write a loop or convert to lowercase first (e.g., using
std::tolowerfrom<cctype>). - Need to split a string? There is no
split()function; usestd::getlinewith a delimiter orfindin a loop. - Need to trim whitespace? No built-in trim; write a small helper using
find_first_not_ofandfind_last_not_of.
Common Pitfalls and Misconceptions
One common mistake is confusing size() with capacity(). size() is the number of characters in use; capacity() is the allocated memory size, which may be larger. Another pitfall: find() returns std::string::npos (which is static_cast<size_t>(-1)) on failure, so always compare with npos, not with -1 directly. Also, c_str() returns a pointer to a null-terminated array that is valid until the string is modified; storing it long-term is dangerous. A common misconception is that std::string is mutable like an array; it is, but modifying it may invalidate iterators and references, so be careful when using at() or operator[] with concurrent modifications.
Performance and Memory Considerations
String operations can be expensive if done repeatedly. For example, s += c in a loop may reallocate memory many times; using reserve() beforehand can reduce reallocations. find() is typically O(n), but the standard does not guarantee a specific algorithm. substr() creates a new string, copying characters, which is O(n). replace() can be O(n) as well. For large strings, consider using std::string_view (C++17) to avoid copies when just reading. Also, std::to_string uses the default locale and may produce unexpected formatting for floating point; for precise control, use std::ostringstream or std::format (C++20).
Alternatives to std::string Functions
For advanced needs, C++ offers other options:
- std::string_view (C++17): a non-owning view of a character sequence, useful for function parameters that only read.
- std::stringstream: for formatted input/output and conversion, e.g.,
std::stringstream ss; ss << 3.14; std::string s = ss.str(); - std::regex: for pattern matching, but it is slower and more complex.
- Third-party libraries like Boost.StringAlgo provide
trim(),split(), and case conversion, which are not in the standard library. - C-style functions like
strlen,strcpyare for raw char arrays and should be avoided in modern C++ due to safety issues.
Frequently Asked Questions
Does C++ have a split function for strings? No, the standard library does not provide a split() function. You can split using std::getline with a delimiter (e.g., std::getline(ss, token, ',')) or by repeatedly calling find() and substr().
What is the difference between size() and length()? They are identical; length() is kept for historical compatibility with C-style strings, but both return the number of characters in the string.
How do I convert a string to an integer in C++? Use std::stoi(s) (since C++11). It throws std::invalid_argument if no conversion could be performed, and std::out_of_range if the value is out of range. For other types, use stol, stoll, stod, etc.
Why does find() return a huge number when not found? Because it returns std::string::npos, which is defined as static_cast<size_t>(-1), the maximum possible value for size_t. Always compare to npos.
Is std::string thread-safe? Individual string objects are not thread-safe for concurrent modification. If multiple threads read the same string, it is safe, but if one writes, you need external synchronization (e.g., a mutex).
Can I use string functions on C-style strings? No, std::string member functions require a std::string object. However, you can convert a C-style string to std::string via std::string(cstr), and you can get a C-style pointer via c_str().
Related
- Data Entry How to Do: Steps, Tools, and Accuracy Tips
- How to Select All Files in a Folder (Windows & Mac)
- Select All Cells in a Range: Excel & Sheets
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Lookup Second Match: 4 Formulas That WorkTo return the second (or any nth) match in Excel, use the FILTER function (Excel 2021/Microsoft 365): =INDEX(FILTER(range,…
- COUNTIF in Excel: Syntax, Examples, and Common FixesIn Excel, use COUNTIF to count cells in one range that meet one condition. If the values you…
- Excel Formula to Calculate Hours WorkedFor a shift that starts in B2, ends in C2, and has an unpaid break entered as a…
- Divide in Excel: Formulas, Examples, and Common ErrorsTo divide in Excel, type an equals sign, enter the number or cell reference you want to divide,…
- Excel MATCH Arguments: What Each One DoesExcel’s MATCH function has three arguments: MATCH(lookup_value, lookup_array, [match_type]). The first two say what to look for and…
- Add a Formula in Excel to Calculate DatesTo calculate a date in Excel, enter a starting date in one cell and use a formula such…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.