C++ string library functions are the standard tools for creating, measuring, changing, searching, comparing, and converting text. Most everyday text work uses std::string and its member functions, declared in <string>; C-style character functions in <cstring> are a separate, lower-level interface.
What the C++ string library provides
std::string is an alias for a specialization of the standard library’s std::basic_string template. It stores a sequence of char values and manages its memory for you. Include <string> to use it, and write std::string unless your code has a deliberate reason to import names from the std namespace.
The name “string functions” can refer to two kinds of operations. Member functions are called on a string object, as in text.size() or text.find(...). Non-member functions and operators work with strings from outside the class, such as std::getline, std::to_string, and the comparison operator ==. Both are part of normal C++ string handling.
Commonly used operations include:
size()andlength()to get the number of stored characters.append(),+=, andpush_back()to add characters or text.insert(),replace(), anderase()to edit part of a string.find(),rfind(), and related functions to locate text.substr()to obtain a substring, andcompare()or==to compare strings.
Creating strings and checking their size
Strings can be initialized from a string literal, copied from another string, or built from a range of characters. For example, std::string city = "Oslo"; creates a string containing four characters. An empty string can be declared as std::string message;. The object manages its own storage, so ordinary assignment and return from functions are much simpler than managing a character array by hand.
Use size() or its equivalent length() to find the number of stored char elements. The result type is std::string::size_type, an unsigned integer type suitable for string sizes. For instance, if city contains "Oslo", city.size() is 4. Prefer this to sizeof(city): sizeof reports the size of the string object itself, not the length of the text it holds.
To access one character, use an index: city[0] refers to the first character. Indexing with [] does not perform the same bounds check as at(). Use city.at(index) when you want an invalid index to raise std::out_of_range rather than access an invalid position. A valid index is less than size(); the position equal to the size is not an ordinary character in the string.
Adding, removing, and changing text
For straightforward concatenation, += is concise and readable: message += "!"; adds an exclamation mark to the end. The append() member function does a similar job, while push_back() adds one character, such as message.push_back('!');. The + operator creates a combined string expression; when repeatedly building a result in a loop, appending to an existing string is often clearer than constructing many intermediate expressions.
Several member functions edit a chosen position. insert(position, text) adds text before that position. erase(position, count) removes up to count characters, and replace(position, count, text) removes a section and puts replacement text in its place. Positions and counts are measured in char elements. Check that positions are sensible, especially when they come from user input or a previous search; an invalid position can cause an exception.
Use clear() to make a string empty, and empty() to test whether it contains no characters. Clearing a string does not require you to free its storage manually. Its capacity() reports how many characters can fit in allocated storage without a reallocation, while reserve(n) can request capacity for at least a given size. These are performance tools, not ways to change the text: a string’s size and capacity are different quantities.
Searching and extracting parts of a string
find() searches forward for a character or sequence of characters and returns the position of the first match. For example, text.find("cat") looks for that sequence. rfind() searches in reverse direction. Related functions include find_first_of(), which searches for any character from a set, and find_first_not_of(), which finds the first character that is not in that set. These can help with simple character-based scanning, though they are not full regular-expression tools.
Every search function returns std::string::npos when it finds no match. Test for that value before using a result as a position. For example, if auto pos = text.find(":");, then pos != std::string::npos means a colon was found. Do not treat a failed search as position zero: zero is a valid location, and npos is a special value.
substr(position, count) returns a new string containing part of the original, starting at position and taking up to count characters. If the count is omitted, it takes the remainder. For example, a string containing "red,blue" can be split around the comma by finding its position and taking substrings before and after it. If the delimiter may be absent, check the search result first; blindly using a failed search position can produce incorrect logic or an exception.
Comparing strings and converting values
For equality, use == and !=; for ordering, use operators such as < or the member compare(). These comparisons are based on the string’s character sequence, not on a language-aware idea of alphabetical order. In particular, ordinary string ordering is not automatically case-insensitive and is not a complete solution for sorting natural-language text according to a locale.
The std::to_string overloads convert several numeric types to a string. The conversion functions std::stoi, std::stol, std::stoll, and their floating-point counterparts parse numeric values from strings. These functions are declared in <string>. Parsing can fail: invalid text may result in std::invalid_argument, and a value outside the destination type’s range may result in std::out_of_range. They can also accept a numeric prefix and stop at a later nonnumeric character, so use the optional position argument if you need to verify how much text was consumed.
For example, converting "42" with std::stoi yields the integer 42, but converting "four" does not. When parsing input, decide how your program should handle errors instead of assuming every string contains a valid number. C++17 also introduced std::from_chars for numeric parsing in <charconv>; it can be useful when you want a low-allocation parsing interface, though floating-point support depends on the standard library implementation.
Reading and writing strings
Include <iostream> for standard input and output. The extraction expression std::cin >> word; reads a whitespace-delimited token: it stops at a space, tab, or newline. That behavior is useful for individual words, but it does not read a full line containing spaces.
Use std::getline(std::cin, line) to read characters through the next newline into a string. A common surprise occurs when formatted input and line input are mixed. After std::cin >> age;, the newline after the number may remain in the input stream, so a following getline can immediately read an empty line. A common fix is to discard the rest of that line with std::getline(std::cin, discard); before reading the next full line. The right approach depends on the input format; clearing a stream’s error state is a separate operation and does not itself remove leftover characters.
std::string versus C-style string functions
C-style string functions are declared in <cstring> and work with null-terminated character arrays or pointers. Familiar examples include std::strlen, std::strcmp, std::strcpy, and std::strcat. They are different from std::string member functions: they do not automatically track a buffer’s capacity, and functions that copy or concatenate require the caller to provide enough destination space.
For most new C++ code, prefer std::string for owned text. It manages storage and provides operations such as append and find without requiring a manually maintained buffer length. C-style interfaces remain relevant when calling older libraries or operating on a C API that explicitly expects a pointer to characters.
A string can be passed to such an API with text.c_str(), which returns a pointer to a null-terminated character sequence. The pointer is meant to be used while the string remains alive and is not changed in a way that invalidates it. Also remember that a C API commonly treats the first null character as the end of its text. A std::string can store an embedded null character, and its size() can include characters after it, but a typical C-string function will stop at that null.
Character encodings and common mistakes
std::string stores bytes as char values; it does not automatically understand Unicode characters or count user-perceived letters. With UTF-8 text, one visible character can take several bytes, so size() reports the byte count, not necessarily the number of displayed characters. Indexing into the middle of a multibyte UTF-8 sequence can also produce invalid text. Programs that need Unicode-aware editing, normalization, or character counting need appropriate Unicode processing rather than assuming each char is one complete character.
Other recurring errors are straightforward to prevent:
- Check for
std::string::nposbefore using a search result as a position. - Use
at()when checked indexing is preferable, or ensure every[]index is in range. - Do not use
sizeof(string)to ask how many characters it contains; usesize(). - Do not pass
c_str()to code that will retain the pointer after the string may be changed or destroyed. - Do not assume string comparisons ignore case or follow the reader’s language-specific alphabet.
Choosing the right string type
Use std::string when a function or object needs to own and modify ordinary byte-based text. If a function only needs to inspect text temporarily, std::string_view, available since C++17 in <string_view>, can provide a lightweight view without copying. A view does not own the characters it refers to, so it must not outlive the original storage. Returning or saving a view to a temporary string can therefore leave a dangling reference.
There are also wide-character types such as std::wstring, but switching to a wide string does not by itself solve every Unicode or internationalization problem. Choose a type based on the interface and encoding requirements of the program. For ordinary application text, a clearly defined UTF-8 convention with std::string is common; for platform APIs, follow the API’s documented character type and encoding.
Frequently Asked Questions
Which header should I include for std::string?
Include <string>. Include other headers, such as <iostream> for stream input and output or <cstring> for C-style string functions, when you use their facilities.
What is the difference between size() and length()?
For std::string, they return the same value: the number of stored char elements. Both count bytes for UTF-8 text, not necessarily visible Unicode characters.
How do I check whether find() found a match?
Compare its result with std::string::npos. A result of zero means the match starts at the first character, so checking whether the result is nonzero would incorrectly reject that valid match.
How do I remove spaces from a string?
There is no single std::string member function that automatically removes every kind of whitespace. You can use standard algorithms such as std::remove_if from <algorithm> together with an erase operation, or build a new string while filtering characters. Decide whether “space” means the ordinary space character or a broader set of whitespace characters.
Is std::string safe to use with C functions?
It can interoperate through c_str() when the C function expects a null-terminated string and only uses the pointer for a valid period. Check the C function’s contract, especially whether it writes to the buffer or retains the pointer; c_str() should not be treated as a writable destination.
Related
- Split in SQL: Practical Methods for Common Databases
- T-SQL STRING_SPLIT: Syntax, Order, and Examples
- JavaScript String Split: Syntax, Examples, and Tips
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Formula for Overtime Hours in Excel: Simple ExamplesFor a daily overtime calculation in Excel, use =MAX(0,(MOD(C2-B2,1)-D2)*24-E2). With a start time in B2, end time in…
- Excel Number Range Formula: Calculate, Count, and ListTo calculate the numerical range—the difference between the largest and smallest values—in cells A2:A10, use =MAX(A2:A10)-MIN(A2:A10). If by…
- Excel FILTER Formula with Multiple Criteria ExplainedIn Excel for Microsoft 365, use FILTER with multiplication between conditions when every criterion must be true, and…
- Excel Formula for Over Budget? Simple IF CheckThe quickest Excel formula to flag an over-budget item is =IF(B2>C2,"Over","OK"), where B2 holds the actual spend and…
- Excel COUNTIFS Between Dates: Formula and ExamplesTo count dates between two boundaries in Excel, use COUNTIFS with the same date range twice: once for…
- Excel NPV Formula Year by Year: How It WorksIn Excel, use =NPV(rate, year_1_cash_flow:year_n_cash_flow)+year_0_cash_flow to calculate net present value when cash flows occur at the end of…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.