A C++ string functions cheat sheet centers on std::string: use size() or length() to count bytes, find() to search, substr() to copy part, and append() or += to add text. Choose std::string_view when you need a non-owning view, and use C-string functions only when an interface specifically requires a null-terminated character array.
What C++ strings are
The standard owning text type is std::string, an alias for std::basic_string<char> provided by the <string> header. It manages its character storage and grows as text is added, so you usually do not need to allocate or terminate a character array yourself. Include <string> and write std::string, or use a project’s chosen namespace convention.
A string stores a sequence of char values. In the common UTF-8 case, those values are bytes, not necessarily complete human-readable characters. Consequently, size() reports the number of stored bytes, and indexing addresses a byte position. A visible accented letter or emoji may occupy multiple bytes. This distinction matters when cutting or counting international text.
Do not confuse a string object with a string literal such as "hello", whose type is a character array, or with a C-style string, which is a character sequence terminated by a null character. C++ strings can work with these forms, but their ownership and termination rules differ.
Quick reference: everyday std::string functions
size()andlength(): return the number of stored characters, which forstd::stringmeans bytes. They are equivalent.empty(): tests whether the string contains no characters. Prefer it to comparingsize()with zero.at(pos): accesses a character with bounds checking; an invalid position throwsstd::out_of_range.operator[](pos),front(), andback(): access characters without the same bounds checking asat(). Ensure the string is nonempty before usingfront()orback().append(text)andoperator+=: add a string, character sequence, or character to the end.push_back(ch)adds one character.insert(pos, text),erase(pos, count), andreplace(pos, count, text): insert, remove, or substitute a range.find(text)andrfind(text): locate the first or last match. A failed search returnsstd::string::npos.substr(pos, count): returns a new string containing a portion of the original.compare(other): compares strings lexicographically; it returns a negative value, zero, or a positive value according to their ordering.c_str()anddata(): provide access to the string’s character storage for APIs that accept character pointers.
Creating strings and changing their contents
Initialize strings directly from literals, combine them with +=, or use named operations when they make the intent clearer. The following short example searches, extracts, and prints a matching part of a string:
#include <iostream>
#include <string>
int main() {
std::string message = "C++ strings are useful";
message += ".";
const std::size_t pos = message.find("strings");
if (pos != std::string::npos) {
std::cout << message.substr(pos, 7) << '\n';
}
}
Here find() returns the position of the match, or the special value npos if it is absent. Checking that result before using it as an index is important: npos is a very large unsigned value, not an ordinary negative error code. substr(pos, count) begins at pos; if count is omitted, it copies through the end. Asking for a count longer than the remaining text simply copies the remaining portion, but a starting position greater than size() throws.
Other useful content-management methods include clear() to remove all characters, resize(n) to set the length, and reserve(n) to request capacity for future growth. Capacity is storage available before another allocation may be needed; it is not the string’s length. Reserving is an optional performance hint, not a requirement for ordinary code.
Searching, comparing, and slicing
The search family covers more than exact substring matching. find_first_of(chars) looks for any character from a supplied set; find_first_not_of(chars) looks for the first character outside that set. The corresponding find_last_of() and find_last_not_of() search from the end. These functions search character sets, not words or regular expressions. For example, find_first_of("aeiou") finds the first lowercase vowel.
Searches can start from an optional position, which is useful for finding repeated matches. After a successful search at pos, a loop can continue from pos + 1 when overlapping matches are allowed, or from pos + pattern.size() when they are not. Always test against npos before adding to or using a returned position.
compare() and the ordinary relational operators compare character sequences lexicographically. That is not the same as language-aware alphabetical sorting: case, accents, and locale-specific collation need more specialized handling. In C++20, starts_with() and ends_with() provide direct prefix and suffix tests. In C++23, contains() provides a direct substring-presence test. For earlier language versions, use find() != std::string::npos for containment.
Choosing std::string, string_view, or a C string
Choose std::string when the function needs to own text, modify it, or keep it after the source goes away. It is the default for most application code. Choose std::string_view when a function only needs to read a character range temporarily and should avoid making a copy. It is available in C++17 through <string_view>, and supports many familiar operations, including size(), find(), and substr().
A view does not own its characters. Returning a view into a local string, or retaining one after its source string is destroyed or changed in a way that invalidates storage, can leave a dangling view. A view also is not guaranteed to end with a null character, so do not pass its data() pointer to a C API that expects a null-terminated string unless you separately ensure termination. Use a C-style character array or pointer when required by a legacy API or a low-level interface, but keep track of its length and termination explicitly.
Converting between text and numbers
For simple conversions, std::to_string(value) creates a string representation of a numeric value. Functions such as std::stoi, std::stol, and std::stod parse strings into numbers; they can throw std::invalid_argument when no conversion is possible and std::out_of_range when the result cannot fit. These parsing functions may accept a valid numeric prefix and leave trailing characters unconsumed. If the whole input must be numeric, use the optional position output to check how much was read.
For numeric parsing or formatting where allocation, exceptions, or locale behavior matter, C++17 provides std::from_chars and std::to_chars in <charconv>. They operate on character ranges and report errors through a result object rather than throwing for ordinary parse failures. They are useful in performance-sensitive code and for predictable machine-readable formats. They do not replace every conversion need: for example, floating-point support has depended on standard-library implementation quality, so check the compiler and library targeted by a project.
Working safely with C-style strings
Use c_str() when an API takes a pointer to a null-terminated sequence, such as a C function accepting const char*. The returned pointer is managed by the string; do not delete it or write through it. The pointer can become invalid after operations that change the string, so do not cache it across modifications. Keep the owning std::string alive for as long as the pointer is used.
Modern C++ strings provide contiguous storage, and data() can expose that storage. A non-const overload allowing modification through data() is available since C++17, but writing must stay within the string’s existing valid character range; it is not a way to increase the string’s length. Use string operations such as append() or resize() to change the length. Also remember that a pointer and a length are often a safer interface than assuming every character range ends at a null terminator.
Common mistakes and how to avoid them
- Using a character count for UTF-8:
size()counts bytes, not Unicode code points or displayed symbols. Use a Unicode-aware library when an operation must treat user-visible characters as indivisible units. - Forgetting to check a search result: Compare positions with
std::string::nposbefore passing them tosubstr(),erase(), or indexing. - Assuming indexing is checked: Use
at()when a checked access is useful. Withoperator[], make sure the position is valid; likewise check for emptiness before callingfront()orback(). - Confusing capacity with size:
reserve()does not add characters. Useresize()if the string needs a particular length. - Keeping a pointer or view too long: A pointer from
c_str()or astring_viewmay no longer be usable after the source is destroyed or modified. Prefer owning a string when lifetime is uncertain. - Using
+repeatedly in a large loop: Repeated concatenation can create temporary strings. Accumulate with+=orappend(), and considerreserve()if the final size is known.
Case conversion and formatting
The standard string class does not provide a member function that converts a whole string to uppercase or lowercase. For basic byte-oriented conversion, use character functions from <cctype>, but pass a value converted to unsigned char before calling functions such as std::tolower. Passing a negative plain char can cause undefined behavior. This technique is not Unicode-aware and may not implement language-specific casing rules.
For general text formatting, consider streams, a formatting library, or std::format where supported by the project’s C++ standard library. std::format is part of C++20, though support can vary by compiler and library version. Formatting tools are often clearer than manually joining many values with +, especially when numbers, padding, or precision are involved.
Frequently Asked Questions
Are std::string size() and length() different?
No. They return the same value for std::string. Both count stored char elements, which usually means bytes, not user-perceived characters.
How do I check whether a string contains a substring?
In C++23 or later, use text.contains(part). In earlier versions, test whether text.find(part) != std::string::npos.
Does substr() modify the original string?
No. substr() returns a new string containing the requested range. To change the original, use operations such as erase(), replace(), or assignment.
What is the difference between std::string and char*?
std::string owns and manages its characters and tracks its length. A char* is only a pointer; it does not by itself say who owns the memory, how long it is, or whether it is null-terminated.
Can I use std::string for Unicode text?
It can store UTF-8 bytes, but its basic functions do not interpret Unicode characters. Use a Unicode-aware library for operations such as counting displayed characters, case folding, or safely cutting text at character boundaries.
Which header contains std::string_view?
Include <string_view> and compile as C++17 or later. The view is non-owning, so its source characters must outlive every use of the view.
Related
- JavaScript .split(): How It Works and When to Use It
- C++ String Erase: How std::string::erase Works
- How to Split an Object in Onshape: A Step-by-Step Guide
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- How to Copy Formulas in Excel to Other Rows: Step by StepTo copy a formula into rows below it in Excel, select the cell that contains the formula and…
- Excel TODAY Formula: Show Today’s Date AutomaticallyTo show today’s date in an Excel cell and have it update, enter =TODAY(). The function returns the…
- Excel LAMBDA Formula Examples for Reusable FunctionsExcel LAMBDA lets you turn a calculation into a reusable function, so you can name it once and…
- What-If Analysis in Excel: How It Works and When to Use ItWhat-If Analysis in Excel is a set of tools for seeing how changing input values affects a formula’s…
- Excel Loan Payment Formula: PMT & How to Use ItThe quickest way to calculate a loan payment in Excel is the PMT function. In its simplest form,…
- Working Hours Calculation Formula in Excel: ExamplesFor a shift that starts in A2 and ends in B2 on the same day, calculate working hours…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.