C++ string functions are operations for creating, examining, searching, changing, and converting text. For most everyday work, use the standard-library std::string type and its member functions; use the separate C-style functions in <cstring> when you specifically need to work with null-terminated character arrays.
What “string functions” means in C++
C++ does not have one universal function named “string.” The phrase usually refers to one of two related interfaces. The modern, general-purpose choice is std::string, declared in the <string> header. It manages a sequence of characters and provides member functions such as size(), find(), and replace(). A typical program uses the std:: namespace prefix:
#include <iostream>
#include <string>
int main() {
std::string language = "C++";
std::cout << language.size() << '\n';
}
The other interface comes from C: functions such as std::strlen and std::strcmp operate on character arrays terminated by a null character, written '\0'. These functions are available through <cstring>. They have different rules from std::string, so it is useful to identify which kind of string a function expects before calling it.
Core std::string functions
Several members answer basic questions about a string or provide access to its characters:
size()andlength()return the number ofcharelements. They are equivalent forstd::string.empty()reports whether the string has no characters. It is clearer than comparingsize()with zero.at(index)accesses a character with bounds checking. If the index is outside the string, it throwsstd::out_of_range.operator[], as intext[index], accesses a character without the same bounds-checking guarantee. Use it when the index is already known to be valid.front()andback()access the first and last characters. Do not call them on an empty string.
For example, with std::string word = "river";, word.size() is 5, and word.at(1) is 'i'. An index starts at zero, so the last valid index is size() - 1 when the string is not empty. These functions count stored char elements, not necessarily the characters a person perceives on screen; Unicode text needs extra care, discussed below.
Searching and comparing text
Use find() to locate a character or substring. It returns the starting index of the first match, or the special value std::string::npos when no match exists. Always compare the result with npos before treating it as an index:
std::string message = "C++ string functions";
auto position = message.find("string");
if (position != std::string::npos) {
std::cout << "Found at " << position << '\n';
}
For that example, the match begins at index 4. Related functions include rfind(), which searches from the end, and find_first_of() or find_first_not_of(), which search using a set of characters. These are useful for tasks such as finding the last slash in a path or skipping a group of separator characters.
For equality, use ordinary operators: ==, !=, <, and their related comparisons. String comparisons are lexicographical: they compare character values in order, not meanings in a language or numeric values embedded in text. Thus, comparing "10" and "2" as strings is not the same as comparing the numbers 10 and 2. The member compare() is available when its ordering result is useful, but most code is easier to read with the operators.
Building and modifying strings
std::string manages its own storage and can grow as text is added. The + operator creates a combined string, while += appends to an existing one. The member append() offers another way to add text. For example:
std::string greeting = "Hello";
greeting += ", ";
greeting.append("world");
greeting.push_back('!');
After these operations, greeting contains Hello, world!. Use insert(position, text) to add characters at a chosen position, erase(position, count) to remove a range, and replace(position, count, text) to substitute one range for another. clear() removes all characters, and substr(position, count) returns a new string containing a portion of the original. If the count is omitted, substr() takes the remaining characters. An invalid starting position for substr() throws std::out_of_range.
Repeated concatenation in a loop can create many temporary strings, especially when assembling a large result. Appending to one string is often clearer; when the approximate final size is known, reserve(size) can request capacity in advance. Capacity is an allocation detail, not the number of characters: size() tells you how much text is currently stored.
C-style string functions and the key difference
The C functions in <cstring> work with pointers to null-terminated character sequences rather than an object that tracks its own length. Common examples are std::strlen(text) for the number of characters before the terminating null, std::strcmp(a, b) for comparison, and std::strchr(text, ch) for finding a character. Their results and expectations differ from the corresponding C++ string members. For example, std::strcmp returns a negative, zero, or positive value according to ordering; it does not return a Boolean equality result.
Buffer size is a major safety concern with C-style operations. A destination array passed to std::strcpy or std::strcat must have enough room for all copied characters plus the terminating null character. If it does not, the program can write outside the array, causing undefined behavior. The programmer also has to ensure the source actually contains a terminator within accessible memory. This is why std::string is generally easier and safer for ordinary text handling. Do not assume that a function is safe simply because its name includes a size limit: for example, strncpy can leave a destination without a terminating null when the source is too long.
Conversion between the forms is possible. A std::string provides c_str(), which returns a pointer to a null-terminated character sequence suitable for APIs that expect one. The pointer is owned by the string, so do not delete it, and do not rely on it after changing or destroying the string. Conversely, a null-terminated character array can be used to construct a std::string, provided it is valid and terminated.
Reading text and converting values
For a whole line of input, use std::getline with an input stream and a string. Unlike operator>> on a string, which normally stops at whitespace, getline reads spaces up to the newline delimiter. If a program first reads a number with std::cin >> value and then calls getline, the newline left in the input stream can make the next line read appear empty. The program needs to handle that leftover delimiter before reading the intended line.
For basic number conversions, std::to_string converts numeric values to strings, while functions such as std::stoi, std::stol, and std::stod parse strings into numbers. The parsing functions can throw exceptions for invalid input or values outside the destination range. They may also accept a valid numeric prefix and leave later characters unparsed, so validate the full input when that matters.
C++17 added the std::from_chars and std::to_chars functions in <charconv> for numeric conversion. They report errors through a result value rather than throwing exceptions, which can suit performance-sensitive or tightly controlled parsing. They work on character ranges, not directly on std::string alone; a string’s data and end position can provide that range. Choose a conversion approach based on error handling and input requirements, not just brevity.
Character handling, Unicode, and newer features
A common misconception is that std::string::size() always counts visible letters. It counts char elements. In UTF-8, a single Unicode code point can use several bytes, and a user-perceived symbol can consist of multiple code points. Consequently, indexing a UTF-8 std::string can land in the middle of a multibyte sequence, and byte-based length is not necessarily the displayed character count. Use a Unicode-aware library or a deliberate decoding strategy when code needs to edit, normalize, or count human text correctly.
For basic character classification and conversion, the <cctype> functions include std::isspace, std::isalpha, and std::tolower. When passing a possibly signed char to these functions, convert it to unsigned char first (while still allowing the special end-of-file value where relevant). Passing a negative plain char value other than EOF has undefined behavior. These C locale functions are not a general solution for Unicode case conversion.
Language versions also add useful string facilities. C++17 introduced std::string_view, a lightweight, non-owning view of character data that can reduce copies when a function only needs to inspect text. Its lifetime must not exceed the lifetime of the underlying characters. C++20 added starts_with() and ends_with() to strings and string views; C++23 added contains() to std::string. Check the compiler’s selected language standard before using these newer members.
Choosing the right function and avoiding mistakes
For typical application code, prefer std::string when you need an owned, changeable string. Use std::string_view for a temporary, read-only view when lifetime is clear, and use C-style arrays only when an interface requires them or when working with existing C APIs. The choice is not merely about spelling: ownership, termination, bounds, and lifetime differ.
- Check
find()results againststd::string::nposbefore using them as positions. - Check indexes before using
operator[]; useat()when a checked access is useful. - Do not confuse the number of bytes or
charelements with the number of visible Unicode characters. - Do not keep a pointer from
c_str()across operations that may change the string. - When working with C buffers, verify destination capacity and null termination rather than assuming they are guaranteed.
- Choose input and numeric conversion functions that let the program detect malformed or incomplete input.
Another frequent error is calling erase() or replace() with positions based on an earlier version of a string after that string has changed. Recalculate positions after modifications, or perform edits in an order that preserves the indexes you still need. String operations can also invalidate pointers, references, or iterators into the string when storage changes. Treat such references as potentially invalid after a non-const operation that might alter its contents or capacity.
Frequently Asked Questions
What is the most commonly used string function in C++?std::string is the common string type, rather than a single function. Its frequently used members include size(), empty(), find(), substr(), and append(); the right one depends on whether you are measuring, searching, extracting, or changing text.
How do I check whether a string contains a word?
Use find() and compare its result with std::string::npos. In C++23, contains() provides a direct Boolean check. If using an earlier language standard, the find() approach works across common C++ versions.
What is the difference between length() and size()?
For std::string, they return the same value: the number of stored char elements. size() is the common container-style spelling, while length() can read naturally when discussing text.
Should I use string or char array in C++?
Use std::string for most owned text because it manages its size and storage. Use a character array or pointer when an API specifically requires a null-terminated buffer, and then carefully manage capacity, termination, and lifetime.
Does std::string support Unicode?
A std::string can store UTF-8 bytes, but its ordinary operations are generally byte-oriented; they do not automatically decode Unicode or count visible characters. Use Unicode-aware processing for operations that must respect code points, grapheme clusters, or language-specific rules.
Related
- D&A on the Balance Sheet: Where It Appears and Why
- How to Add Speaker Notes to Your PowerPoint Slides
- What Is Balance in Accounting? Meaning and Examples
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Median in Excel Based on Criteria: Formulas and ExamplesIn Excel for Microsoft 365, calculate a median for matching rows with =MEDIAN(FILTER(B2:B20,(A2:A20="East")*ISNUMBER(B2:B20))). This example returns the median…
- Excel Formula for Dates Before Today: Flag, Filter, FormatWith dates in A2:A100, use =A2<TODAY() to test whether the date in A2 is before today; Excel returns…
- Excell Battery SDS: How to Find the Right SheetAn Excell battery does not have one universal SDS: the correct safety data sheet depends on the battery’s…
- Excel SUMIF Between Dates: Multiple Criteria ExplainedTo sum values in Excel for Microsoft 365 that fall between two dates and meet other conditions, use…
- Microsoft Excel Calendar Formula: Build a Monthly ViewIn Microsoft Excel for Microsoft 365, enter a year in B1 and a month number in C1, then…
- Excel Formula for Splitting Text in a Cell by DelimiterIn Microsoft 365 or Excel 2024, use TEXTSPLIT to divide text from one cell into separate cells. If…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.