The most common string functions in C++ are member functions of the std::string class (from <string>), including length()/size(), empty(), at(), append()/+=, insert(), erase(), replace(), find(), substr(), compare(), and c_str(). You also have free functions like std::getline() and std::stoi() for input and conversion. This article explains each with concrete examples, how to choose between them, common pitfalls, and safety considerations.
Background: C-Style Strings vs. std::string
Before C++ had a standard string class, programmers used C-style strings: null-terminated arrays of char, like char name[] = "Alice";. Those require manual memory management and error‑prone functions like strcpy() and strlen() from <cstring>. The C++ std::string class (introduced in the C++98 standard) wraps the array, manages its own memory, and provides safe member functions. Modern C++ code should prefer std::string over raw character arrays unless you are working with legacy code or a C API. The std::string class is defined in the header <string> and is part of the Standard Template Library (STL).
Essential Member Functions and How They Work
Here are the most frequently used member functions, with a short example for each. Assume std::string s = "Hello"; unless stated otherwise.
length()/size()– return the number of characters (both are identical).s.length()returns 5.empty()– returnstrueif the string has zero characters.s.empty()isfalse.at(i)/operator[]– access the character at indexi.s.at(1)returns'e'.at()throwsstd::out_of_rangeifiis invalid;operator[]does not check bounds (undefined behavior).append(str)/operator+=– add characters to the end.s += " World";makessequal"Hello World".insert(pos, str)– insert a substring at positionpos.s.insert(5, " beautiful");yields"Hello beautiful".erase(pos, len)– removelencharacters starting atpos.s.erase(1, 3);changes"Hello"to"Ho".replace(pos, len, str)– replacelencharacters withstr.s.replace(0, 5, "Hi");gives"Hi".find(str)– returns the index of the first occurrence ofstr, orstd::string::nposif not found.s.find("ll")returns 2.substr(pos, len)– returns a new string that is a copy of the substring.s.substr(1, 3)returns"ell".compare(str)– lexicographic comparison; returns 0 if equal, negative if less, positive if greater.s.compare("Hello")returns 0.c_str()– returns aconst char*pointer to a null‑terminated array, useful when calling C functions. Do not store the pointer and then modify the string – it may be invalidated.
Example: std::string s = "C++"; s.append(" is fun"); std::cout << s.substr(0, 3); prints C++.
Free Functions and Conversions
Besides member functions, the <string> header provides non‑member functions you will use daily:
std::getline(input_stream, str)– reads a whole line (including spaces) until a newline. Example:std::getline(std::cin, line);std::stoi(),std::stol(),std::stod()– convert a string to an integer, long, or double.std::stoi("42")returns 42. These throwstd::invalid_argumentif the string is not a number andstd::out_of_rangeif the value is too large.std::to_string()– converts a number to a string.std::to_string(3.14)returns"3.140000"(note the fixed decimal places).std::swap()– swaps two strings efficiently.std::swap(a, b);
For case‑insensitive comparisons or splitting, you often combine these with algorithms from <algorithm> (e.g., std::transform to lowercase).
How to Choose the Right Function
Selection depends on what you need to do:
- Get length or check empty? Use
size()orempty()– neverstrlen()on astd::string(it won’t compile). - Concatenate? Use
+=orappend().append()is more flexible (can append a substring). - Search for a substring? Use
find(). Check the result againststd::string::npos. - Extract a part? Use
substr(). - Modify in place? Use
insert(),erase(), orreplace(). - Compare for equality? Use
==(which callscompare()internally) orcompare()if you need ordering (e.g., for sorting). - Pass to a C function? Use
c_str().
For simple tasks, prefer the most readable form. For example, if (s == "done") is clearer than if (s.compare("done") == 0).
Common Problems and Pitfalls
Even experienced programmers hit these issues:
- Off‑by‑one errors with
substr()–substr(pos, len)takes a starting index and a length, not an end index.s.substr(1, 3)gives characters at indices 1,2,3 – not 1 through 3 inclusive of index 4. - Forgetting
std::string::npos–find()returns a huge value (usuallysize_tmax) when not found. Comparing directly to-1works but is less clear; always usenpos. - Modifying a string while iterating – if you call
erase()orinsert()inside a loop, indices shift. Use a reverse loop or collect positions first. - Using
operator[]out of bounds – this is undefined behavior, not an exception. Useat()when you need safety. - Storing
c_str()and then modifying the string – the pointer becomes invalid. Copy the C‑string if you need it later. - Assuming
std::stoi()handles whitespace – it does skip leading whitespace, but if the string is empty or starts with non‑digits, it throws.
Performance and Cost Considerations
Most std::string functions are O(n) in the length of the string, but some have nuances:
length(),empty(),at()are O(1).substr()copies the substring, so it is O(len).find()is O(n*m) in the worst case (naive search), but typical implementations are efficient.append()and+=amortized O(1) per character, but may reallocate the internal buffer when capacity is exceeded.insert()anderase()at the beginning are O(n) because they shift characters.
If you do many insertions at the front, consider std::deque<char> or building the string in reverse. For heavy concatenation, reserve capacity with s.reserve(n) to avoid repeated reallocations.
Safety and Best Practices
- Always check
find()results againstnposbefore using the index. - Prefer
at()overoperator[]when indices come from user input or calculations that might be out of range. - When converting strings to numbers, wrap
stoi()etc. in try‑catch blocks to handle invalid input gracefully. - Use
std::string_view(C++17) when you need a read‑only view of a string without copying – it is safer and faster for function parameters. - Never return a reference to a local string – that is a dangling reference.
- For multi‑threaded code, note that
std::stringis not thread‑safe; protect shared strings with mutexes.
Alternatives: std::string_view, char arrays, and third‑party libraries
For read‑only operations, std::string_view (C++17) is a lightweight non‑owning view. It avoids copying and is ideal for function parameters that only inspect the string. Example: void print(std::string_view sv) { std::cout << sv; }. For legacy C code, you still need const char*. If you need regular expressions, use std::regex (though it is slow) or a library like Boost.Regex. For parsing, std::stringstream is useful for tokenizing. For very large texts, consider std::vector<char> or memory‑mapped files, but that is beyond typical string functions.
Frequently Asked Questions
What is the difference between size() and length()?
There is no difference. Both return the number of characters in the string. length() is a legacy name from earlier C++ standards, and size() is consistent with other STL containers. Use either; they are identical.
How do I check if a string contains a substring?
Use find() and compare against std::string::npos. For example: if (s.find("needle") != std::string::npos) { /* found */ }. In C++23, you can use s.contains("needle") directly.
Why does std::stoi() throw an exception?
stoi() throws std::invalid_argument if no conversion could be performed (e.g., the string is empty or starts with letters) and std::out_of_range if the value is too large for an int. You must catch these exceptions or validate the input first.
Can I modify a string while iterating over it?
Yes, but carefully. If you use a range‑based for (char& c : s), you can modify characters in place. If you insert or erase elements, the iterators are invalidated. Use indices or a reverse loop for erasing.
What does c_str() return and when should I use it?
c_str() returns a const char* pointing to a null‑terminated array that contains the same characters as the string. Use it when calling C functions like fopen() or printf(). The pointer is only valid until the string is modified or destroyed, so copy it if you need it later.
Is std::string faster than char*?
For most operations, std::string is comparable in speed and often faster due to optimizations like small string optimization (SSO). It also avoids manual memory errors. Raw char* can be faster in extremely performance‑critical loops, but the difference is usually negligible. Prefer std::string for safety and clarity.
Related
- How to Create a Fan Number in Excel
- Java Code to Split String: Methods & Examples
- Enum in SQL Server: How to Use It & Why It Doesn’t Exist
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Sum of Filtered Data: SUBTOTAL, AGGREGATE & FILTERTo sum only the rows currently visible after filtering in Excel, put =SUBTOTAL(9,C2:C7) in a cell outside the…
- Replace a Circular Reference With an Excel FormulaYes—replace a circular reference by rewriting the calculation so it uses input cells or earlier results, rather than…
- Excel Formula to Capitalize Names: What PROPER Gets RightTo capitalize names in Excel, enter =PROPER(A2) in a helper column when the name is in A2. PROPER…
- Excel Sort Examples: Rows, Text, Dates, and Custom ListsTo sort a worksheet in Excel for Microsoft 365 on Windows, select a cell in the data, then…
- Slicers for Excel Columns: Filter a Table or PivotTableYes. In Excel for Microsoft 365 on Windows, you can add a slicer for a column in an…
- Excel Round to Nearest Quarter: Formula & StepsTo round a number to the nearest quarter (0.25) in Excel, use the formula =MROUND(A1, 0.25). This rounds…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.