In C++, string functions are operations for creating, inspecting, searching, and changing text. For most C++ programs, use std::string from the <string> header and its member functions, such as size(), find(), substr(), and replace(); use functions from <cstring> when working with null-terminated C-style character arrays.
What “string functions” means in C++
C++ does not have one single function called “string functions.” The phrase usually refers to the many operations offered by the standard library’s std::string type. A string is an object that manages a sequence of characters and provides operations for common tasks, so you generally do not need to track its length or allocate its storage yourself.
The name std::string is an alias for std::basic_string<char>. The same template supports other character types, including wchar_t, but ordinary text in many programs uses std::string. Its functions are members of the object: for example, text.find("cat") searches the string named text.
Some related operations are free functions rather than members. For example, std::getline reads a line into a string, and std::to_string converts supported numeric values to text. Knowing this distinction helps when looking up examples or compiler errors.
Include the right header and create a string
Include <string> to use std::string. The standard library places it in the std namespace, so either qualify its name as std::string or bring the name into scope. Qualifying it is often clearer in examples and larger programs.
#include <iostream>
#include <string>
int main() {
std::string message = "Hello";
message += ", C++!";
std::cout << message << '\n';
}
This program constructs a string from a string literal, appends more text with +=, and writes the result. A literal such as "Hello" is not itself an std::string; the assignment constructs a string object from it. The + operator can also join strings and compatible character sequences, while += adds text to an existing string.
Everyday inspection and access functions
Several member functions answer basic questions about a string. size() and length() return the same value: the number of stored char elements. empty() reports whether there are no elements. capacity() reports how much storage is available before the string needs to expand; it is mainly useful for understanding or optimizing allocation, not for determining the text’s length.
text.size()ortext.length(): get the number of characters stored.text.empty(): check whether the string contains no characters.text.clear(): remove all characters, leaving an empty string.text.at(index): access a character with bounds checking; it throwsstd::out_of_rangeif the index is invalid.text[index]: access a character without bounds checking.
For example, if text is "pear", its size is 4 and text.at(1) is 'e', because indexing starts at zero. Use at() when a checked access is useful, especially when the index comes from input. With [], the program must ensure the index is valid. Neither function should be used with an index outside the string’s valid character range.
Searching and extracting parts of a string
The find() member searches for a character or substring and returns the position where the first match begins. If there is no match, it returns the special value std::string::npos. Always check for that value before treating a search result as a valid position; it is not the same as an ordinary index.
std::string text = "C++ string functions";
std::size_t position = text.find("string");
if (position != std::string::npos) {
std::string word = text.substr(position, 6);
}
Here, position is 4 and word becomes "string". substr(start, count) creates a new string beginning at start, containing up to count characters. If the count extends past the end, the result simply ends at the string’s end. A starting position beyond the string’s size causes substr() to throw std::out_of_range.
Other useful search members include rfind(), which searches from the end, and find_first_of(), which finds the first character matching any character in a supplied set. For example, text.find_first_of("aeiou") locates the first lowercase vowel. These functions perform character or substring searches; they do not automatically apply case-insensitive matching or linguistic rules.
Changing, joining, and comparing strings
Strings can be edited with member functions and operators. append() adds characters at the end, insert() adds them at a position, erase() removes a range, and replace() swaps a range for other text. The += operator is a concise way to append. These operations modify the string object they are called on, unlike substr(), which returns a separate string.
For instance, starting with std::string name = "Mira Lee";, name.replace(5, 3, "Patel"); changes it to "Mira Patel". The position and count describe the characters to replace, beginning at index 5. When an editing position is invalid, the applicable operation can throw std::out_of_range; check positions carefully if they come from a search or user input.
For equality and ordering, use familiar operators such as ==, !=, and <. They compare string contents lexicographically, based on character values, rather than comparing object addresses. The member function compare() is available when code needs its comparison result: it returns a negative value, zero, or a positive value depending on whether the string compares before, equal to, or after the other string. Do not assume it returns exactly -1 or 1.
Reading input and converting numbers
std::getline() is useful when input may contain spaces. With a line-oriented input stream, std::getline(std::cin, line) reads through the newline and stores the line’s contents in line, without storing the delimiter. By contrast, std::cin >> line ordinarily stops at whitespace, so it reads only the next word.
A common input surprise occurs when formatted extraction is followed by getline(). After std::cin >> number, the newline typed after the number can remain in the input stream. The next getline() may consume that newline and return an empty line. One solution is to discard the rest of the line before reading the next full line, using std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') after including <limits>. This is appropriate when the intention is to move to the next line; input handling should match the program’s expected format.
For simple conversions, std::to_string() makes a string from supported numeric types. The conversion functions std::stoi(), std::stol(), and related functions parse numbers from strings. They can throw std::invalid_argument when no conversion is possible and std::out_of_range when the value cannot fit the requested type. If input may contain extra characters, use the optional position parameter or a parsing facility suited to the format rather than assuming the whole string was consumed.
std::string versus C-style string functions
C++ also provides C library functions for null-terminated character arrays through <cstring>. Examples include std::strlen() for length, std::strcmp() for comparison, and std::strcpy() for copying. These functions operate on character pointers and rely on a terminating null character to mark the end of the text.
For new code, std::string is usually the more convenient choice: it manages its own storage, tracks its length, and offers operations such as searching and replacement. C-style strings still appear in C APIs, older code, and interfaces that explicitly require a character pointer. A string can provide a pointer to its null-terminated character sequence with c_str(); that pointer is owned by the string, so do not keep using it after the string is destroyed or changed in a way that invalidates its storage.
A C-style function sees a null character as the end of its input. An std::string, however, can contain a null character within its stored sequence. For example, a string constructed with an explicit length can hold bytes after an embedded null. Passing its c_str() to a function such as strlen() will stop at that embedded null, so the C function may report a shorter length than string.size(). This distinction matters when processing binary data or text that can contain null bytes.
Common mistakes and practical limits
- Forgetting
npos: using a failedfind()result as an index can produce incorrect logic. Compare the result withstd::string::nposfirst. - Confusing characters with bytes: for
std::string, size countscharelements. If the text is UTF-8, a visible character such as an accented letter or emoji can occupy multiple bytes.size()is not a count of user-perceived characters. - Expecting automatic case folding: ordinary comparisons and searches are case-sensitive.
"Cat"and"cat"are different sequences unless the program deliberately normalizes or compares them using an appropriate method. - Using an old pointer after editing: operations that change a string can invalidate pointers, references, and iterators into its character storage. Reacquire them after modifying the string.
- Assuming every operation is free: building a new result or inserting text can require allocation and copying. For performance-sensitive code, avoid unnecessary repeated concatenation in loops; collecting pieces or reserving capacity may help, but should be guided by profiling.
As a useful version note, C++20 adds convenience members such as starts_with() and ends_with() for checking prefixes and suffixes. Earlier language versions can perform equivalent checks with comparisons or suitable search operations. The exact set of available library features depends on both the C++ language standard selected and the compiler’s standard library support.
Frequently Asked Questions
What is the most commonly used string type in C++?std::string is the usual choice for sequences of ordinary char characters. Include <string> and write std::string unless your program has a specific need for another character type or a C-style character array.
What is the difference between size() and length()?
For std::string, they are equivalent member functions and return the same number of stored characters. Neither counts Unicode graphemes; for UTF-8 text, the result is a byte-oriented count of char elements.
How do I check whether a substring exists?
Call find() and compare the result with std::string::npos. A result other than npos is the starting position of a match; npos means no match was found.
How do I join two strings?
Use + to create a combined string, or use += or append() to add text to an existing string. For example, first + second returns a combined result, while first += second changes first.
Should I use std::string or char[]?
Prefer std::string for most C++ text because it manages size and storage and provides convenient operations. Use a character array or pointer when an interface specifically requires a C-style string or when interoperating with code built around that representation.
Related
- Excell Battery P/N 2EXL7431-001: What It Means
- Y Balance Test: How to Perform and Calculate Scores
- How to Add Transitions in PowerPoint: Steps and Tips
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Formula for Age at a Certain Date Using DATEDIFTo calculate someone’s age on a particular date in Excel, use =DATEDIF(A2,B2,"Y"), where A2 contains the birth date…
- Abby Lawson Budget Spreadsheet: Find the Right FileIf you’re looking for an Abby Lawson budget spreadsheet, the name alone does not identify a confirmed official…
- Excel Running Total Formula: Step-by-StepThe simplest Excel formula for a running total in a column is =SUM($B$2:B2) entered in the first data…
- Excel Power Automate Filter Query: Syntax and ExamplesIn Power Automate, filter Excel table rows by entering an OData-style condition in the Filter Query field of…
- Excel Formula for Percentage of Total: Clear ExamplesTo calculate a percentage of a total in Excel, divide the part by the total: if the value…
- Excel: How to Hide Columns to the Right of Your DataTo hide every column to the right of your data in Excel for Microsoft 365 on Windows, select…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.