Common String Functions in C++ (with Examples)

Formulas & functions · Updated November 23, 2026

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() – returns true if the string has zero characters. s.empty() is false.
  • at(i) / operator[] – access the character at index i. s.at(1) returns 'e'. at() throws std::out_of_range if i is invalid; operator[] does not check bounds (undefined behavior).
  • append(str) / operator+= – add characters to the end. s += " World"; makes s equal "Hello World".
  • insert(pos, str) – insert a substring at position pos. s.insert(5, " beautiful"); yields "Hello beautiful".
  • erase(pos, len) – remove len characters starting at pos. s.erase(1, 3); changes "Hello" to "Ho".
  • replace(pos, len, str) – replace len characters with str. s.replace(0, 5, "Hi"); gives "Hi".
  • find(str) – returns the index of the first occurrence of str, or std::string::npos if 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 a const 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 throw std::invalid_argument if the string is not a number and std::out_of_range if 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() or empty() – never strlen() on a std::string (it won’t compile).
  • Concatenate? Use += or append(). append() is more flexible (can append a substring).
  • Search for a substring? Use find(). Check the result against std::string::npos.
  • Extract a part? Use substr().
  • Modify in place? Use insert(), erase(), or replace().
  • Compare for equality? Use == (which calls compare() internally) or compare() 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 (usually size_t max) when not found. Comparing directly to -1 works but is less clear; always use npos.
  • Modifying a string while iterating – if you call erase() or insert() 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. Use at() 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() and erase() 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 against npos before using the index.
  • Prefer at() over operator[] 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::string is 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

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.