C++ String Functions: How to Use Them

Formulas & functions · Updated November 22, 2026

String functions in C++ let you manipulate text easily—finding substrings, changing case, comparing, concatenating, and extracting parts. This guide covers the essential functions from the <string> header and how to use them correctly. You’ll need a C++ compiler (like GCC, Clang, or MSVC) and a basic understanding of variables and functions.

What You’ll Need

  • A C++ compiler (e.g., g++ on Linux, MinGW on Windows, or Xcode on macOS)
  • A text editor or IDE (VS Code, Code::Blocks, Visual Studio, etc.)
  • Basic knowledge of C++ syntax: declaring variables, calling functions, and using std::cout

Step-by-Step

  1. Include the string header. At the top of your file, add #include <string> and #include <iostream> for output. Use using namespace std; to avoid typing std:: every time (or keep the prefix for clarity).
  2. Declare and initialize strings. Create a string variable with a literal: string greeting = "Hello"; or an empty one: string name;. Strings are mutable, so you can change them later.
  3. Get the length. Use length() or size()—they are identical. Example: int len = greeting.length(); returns 5 for “Hello”.
  4. Access characters. Use the [] operator or at(). The index starts at 0. char c = greeting[0]; gives ‘H’. at() is safer because it throws an exception if you go out of bounds.
  5. Concatenate strings. Use the + operator or append(). Example: string full = greeting + " World"; results in “Hello World”. append() works similarly: greeting.append(" World"); modifies the original.
  6. Compare strings. Use ==, !=, <, > for lexicographic comparison. Example: if (str1 == str2). For case-insensitive comparison, convert both to lowercase first (see step 8).
  7. Find a substring. Use find(). It returns the index of the first occurrence, or string::npos if not found. Example: size_t pos = greeting.find("ell"); returns 1. Always check if (pos != string::npos) before using the result.
  8. Extract a substring. Use substr(). Syntax: string part = str.substr(start_index, length);. If you omit length, it goes to the end. Example: string sub = "Hello World".substr(6, 5); gives “World”.
  9. Change case. There is no built-in to uppercase/lowercase a whole string. Use a loop with toupper() or tolower() from <cctype>. Example: for (char &c : str) c = toupper(c); modifies each character in place.
  10. Replace part of a string. Use replace(). Syntax: str.replace(start_index, length, new_text);. Example: str.replace(0, 5, "Goodbye"); replaces the first 5 characters.
  11. Insert or erase. insert(pos, text) inserts at position; erase(pos, len) removes characters. Example: str.insert(5, " there"); inserts after the 5th index (which is after “Hello”).
  12. Convert to C-string (if needed). Use c_str() to get a const char* for functions that expect C-style strings. Example: const char* cstr = str.c_str();.
  13. Check if empty. Use empty() which returns true if the string has zero characters. Example: if (str.empty()).
  14. Clear or resize. clear() empties the string. resize(n) changes the length, padding with null characters if larger.

Common Mistakes

  • Forgetting to include <string>. This causes compile errors like ‘string’ not found.
  • Using find() without checking npos. If the substring isn’t found, find() returns a huge number; using it as an index will crash or cause undefined behavior.
  • Off-by-one errors with substr(). Remember the second parameter is the length, not the end index. substr(0, 3) gives characters at indices 0,1,2.
  • Modifying a string while iterating with a range-based loop. If you change the string’s size (insert/erase) inside a for-each loop, the loop may behave unpredictably.
  • Using c_str() after the string is modified. The pointer becomes invalid; use it immediately or copy the data.
  • Comparing with == when you meant case-insensitive. “Hello” != “hello”. Convert both to same case first.

Tips

  • Prefer std::string over C-style char[] arrays—it’s safer and has built-in functions.
  • Use auto for the return of find() to avoid type mismatch: auto pos = str.find("x");.
  • To split a string by a delimiter, use a loop with find() and substr(). For advanced splitting, consider std::getline with a stringstream.
  • For repeated concatenation in a loop, use += or append() rather than + to avoid creating many temporary strings.
  • Remember that size() returns size_t (unsigned). Compare with another size_t or cast to avoid signed/unsigned warnings.
  • If you need to pass a string to a function that expects a C-string, use c_str() but be aware it’s read-only.

Troubleshooting

  • Compile error: ‘string’ does not name a type. Add #include <string> and ensure you have using namespace std; or use std::string.
  • Program crashes when using at() or [] with an invalid index. Check your index is within 0 to size()-1. Use at() to get an exception instead of a crash.
  • find() returns a large number even though the substring exists. That’s normal—it returns the index. If it’s npos, it means not found. Print the position to debug.
  • String is not modified after calling toupper() in a loop. Make sure you’re modifying the character in place: for (char &c : str) (note the reference &). Without it, you’re changing a copy.
  • Getting wrong substring. Double-check the start index and length. For example, str.substr(1, 3) gives characters at positions 1,2,3—not 1,2,3,4.
  • Linker errors about std::string functions. This usually means you forgot to compile with the standard library, or you’re mixing C and C++ compilation. Ensure your file has a .cpp extension and you’re compiling with a C++ compiler (not C).

Frequently Asked Questions

  • What is the difference between size() and length()? None—both return the number of characters. length() is traditional, size() is consistent with other STL containers.
  • How do I convert a string to an integer? Use std::stoi(str) (or stol, stod for long/double). Include <string>. It throws std::invalid_argument if conversion fails.
  • How do I convert an integer to a string? Use std::to_string(number). Example: string s = to_string(42); gives “42”.
  • Can I use + to concatenate a string and a number? No, you must convert the number first: string s = "Value: " + to_string(10);.
  • How do I check if a string starts with a certain prefix? Use str.compare(0, prefix.length(), prefix) == 0 or str.rfind(prefix, 0) == 0 (C++20 has starts_with()).
  • Why is my string not empty after calling clear()? clear() sets size to 0, but the capacity remains. Use shrink_to_fit() if you need to free memory, but it’s not guaranteed.

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.