String Handling Functions in C++ (with Examples)

Formulas & functions · Updated November 23, 2026

String handling functions in C++ are the tools provided by the <string> header (the std::string class) and the older <cstring> header (C-style functions like strlen and strcpy). In modern C++, you should almost always use std::string because it manages memory automatically, offers member functions for common operations, and integrates with the standard library. This article explains the key functions, how they work, and common pitfalls.

Background: C-Style Strings vs. std::string

Before C++ had its own string class, programmers used C-style strings: arrays of char terminated by a null character ('\0'). Functions like strlen(), strcpy(), and strcat() operate on these arrays, but they require manual memory management and are prone to buffer overflows. std::string was introduced to solve these problems. It is a class that manages a dynamic character array, tracks its length, and provides a rich set of member functions. The <string> header is part of the C++ Standard Library, and std::string is defined in the std namespace.

Core std::string Member Functions

Here are the most commonly used member functions of std::string, with examples. Assume std::string s = "Hello"; unless stated otherwise.

  • Length and capacity: s.length() or s.size() returns the number of characters (both do the same). s.capacity() returns the allocated storage size, which may be larger than the length.
  • Access: s[i] returns the character at index i (no bounds check). s.at(i) does a bounds check and throws std::out_of_range if i is invalid. s.front() and s.back() return first and last characters.
  • Concatenation: Use + operator: std::string t = s + " World"; or s += " World"; to append in place.
  • Comparison: Use ==, !=, <, etc. They compare lexicographically. Example: if (s == "Hello").
  • Substring: s.substr(pos, len) returns a new string starting at pos with length len. If len is omitted, it goes to the end. Example: s.substr(1, 3) returns "ell".
  • Find: s.find("ell") returns the index of the first occurrence, or std::string::npos if not found. s.rfind() searches from the end. s.find_first_of() and s.find_last_of() find any character from a given set.
  • Modification: s.insert(pos, str), s.erase(pos, len), s.replace(pos, len, str), s.push_back(ch), s.pop_back(), and s.clear() to empty the string.
  • C-string conversion: s.c_str() returns a const char* pointer to a null-terminated array. s.data() returns a pointer to the internal buffer (since C++11, it is also null-terminated).

Working with C-Style Functions (cstring)

If you must interoperate with legacy code or C libraries, you may need the C functions. They are declared in <cstring> (or <string.h>). Key functions:

  • strlen(const char* s) – returns length without the null terminator.
  • strcpy(char* dest, const char* src) – copies src to dest (no bounds check).
  • strncpy(char* dest, const char* src, size_t n) – copies at most n characters, but may not null-terminate if n is too small.
  • strcat(char* dest, const char* src) – appends src to dest (no bounds check).
  • strcmp(const char* s1, const char* s2) – returns negative, zero, or positive based on lexicographic order.
  • strchr(const char* s, int c) – finds first occurrence of character c.

These functions require you to manage the destination buffer size. For example, to copy a string safely, you must ensure the destination has enough space. Using std::string avoids these risks entirely.

How to Choose: std::string vs. C-String Functions

For new C++ code, always prefer std::string. It is safer, more intuitive, and supports modern features like range-based for loops. Use C-style functions only when you are interfacing with a C API that expects char* or const char*. Even then, you can convert a std::string to a C-string with c_str() for read-only access. If you need to modify a C buffer, you can copy the string into a std::vector<char> or a raw array with proper size checks.

Common Problems and Pitfalls

  • Buffer overflows: Using strcpy or strcat without checking destination size can overwrite memory. Always use std::string or strncpy/strncat with exact sizes.
  • Off-by-one errors: C-strings require a null terminator. Forgetting to allocate space for it is a classic mistake.
  • Finding failures: find() returns npos (which is static_cast<size_t>(-1)). Comparing the result to 0 is wrong; always compare to std::string::npos.
  • Modifying while iterating: If you use iterators and then call insert or erase, iterators may be invalidated. Be careful with loops.
  • Memory overhead: std::string may allocate more memory than the string length (capacity). This is normal and improves performance.

Performance and Efficiency Considerations

std::string operations are generally efficient. Concatenation using += is amortized O(1) per character because the string grows geometrically. However, repeated concatenation like s = s + "a" creates a temporary and can be O(n) each time; prefer s += "a". For heavy string building, consider std::ostringstream or std::string::reserve() to pre-allocate capacity. The std::string class uses the small string optimization (SSO) in most implementations, which stores short strings (typically up to 15 characters) on the stack, avoiding heap allocation.

Safety and Best Practices

  • Always use std::string unless there is a compelling reason not to.
  • When using C functions, never write to a buffer without knowing its size. Use strncpy and explicitly null-terminate the result if needed.
  • Check the return of find() against std::string::npos.
  • Use s.at(i) when you need bounds checking; otherwise, s[i] is faster but undefined behavior if out of range.
  • Prefer std::string_view (C++17) for read-only parameters to avoid copies.
  • Remember that c_str() returns a pointer that becomes invalid if the string is modified. Do not store it long-term.

Alternatives: std::string_view and Other Libraries

Since C++17, std::string_view provides a non-owning view of a string (a pointer and length). It is ideal for function parameters that only read the string, avoiding copies. It does not manage memory and cannot be modified. For more advanced string processing, libraries like Boost.StringAlgo provide algorithms like split and trim, which are not in the standard library. In C++20, std::string gained starts_with() and ends_with() member functions, and C++23 added contains().

Frequently Asked Questions

How do I convert a std::string to an integer? Use std::stoi(s) (or stol, stoll, stof, etc.) from <string>. It throws std::invalid_argument if no conversion could be performed and std::out_of_range if the value is out of range. Example: int num = std::stoi("123");.

How do I split a string by a delimiter? The standard library does not have a direct split function. A common approach is to use std::getline with a std::stringstream for single-character delimiters, or write a loop using find() and substr(). For example, to split by comma, you can use a std::istringstream and std::getline(ss, token, ',').

Why does my string comparison with == not work? For std::string, == compares the content, so it works. If you are using C-style strings (char arrays), == compares pointer addresses, not content. Use strcmp() instead. This is a common mistake when mixing C and C++ code.

What is the difference between size() and length()? They are identical. Both return the number of characters in the string. size() is consistent with other STL containers, while length() is more intuitive for strings. Use either.

How do I trim whitespace from a string? The standard library does not have a trim function. You can implement it manually using find_first_not_of and find_last_not_of with substr. For example: s.substr(s.find_first_not_of(" \t\n"), s.find_last_not_of(" \t\n") - s.find_first_not_of(" \t\n") + 1).

Can I modify a string returned by c_str()? No. c_str() returns a const char*, so you cannot modify it. If you need a mutable C-style buffer, copy the string into a std::vector<char> or a raw array.

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.