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
- Include the string header. At the top of your file, add
#include <string>and#include <iostream>for output. Useusing namespace std;to avoid typingstd::every time (or keep the prefix for clarity). - 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. - Get the length. Use
length()orsize()—they are identical. Example:int len = greeting.length();returns 5 for “Hello”. - Access characters. Use the
[]operator orat(). 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. - Concatenate strings. Use the
+operator orappend(). Example:string full = greeting + " World";results in “Hello World”.append()works similarly:greeting.append(" World");modifies the original. - Compare strings. Use
==,!=,<,>for lexicographic comparison. Example:if (str1 == str2). For case-insensitive comparison, convert both to lowercase first (see step 8). - Find a substring. Use
find(). It returns the index of the first occurrence, orstring::nposif not found. Example:size_t pos = greeting.find("ell");returns 1. Always checkif (pos != string::npos)before using the result. - 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”. - Change case. There is no built-in to uppercase/lowercase a whole string. Use a loop with
toupper()ortolower()from<cctype>. Example:for (char &c : str) c = toupper(c);modifies each character in place. - 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. - 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”). - Convert to C-string (if needed). Use
c_str()to get aconst char*for functions that expect C-style strings. Example:const char* cstr = str.c_str();. - Check if empty. Use
empty()which returns true if the string has zero characters. Example:if (str.empty()). - 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 checkingnpos. 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::stringover C-stylechar[]arrays—it’s safer and has built-in functions. - Use
autofor the return offind()to avoid type mismatch:auto pos = str.find("x");. - To split a string by a delimiter, use a loop with
find()andsubstr(). For advanced splitting, considerstd::getlinewith a stringstream. - For repeated concatenation in a loop, use
+=orappend()rather than+to avoid creating many temporary strings. - Remember that
size()returnssize_t(unsigned). Compare with anothersize_tor 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 haveusing namespace std;or usestd::string. - Program crashes when using
at()or[]with an invalid index. Check your index is within0tosize()-1. Useat()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’snpos, 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::stringfunctions. This usually means you forgot to compile with the standard library, or you’re mixing C and C++ compilation. Ensure your file has a.cppextension and you’re compiling with a C++ compiler (not C).
Frequently Asked Questions
- What is the difference between
size()andlength()? 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)(orstol,stodfor long/double). Include<string>. It throwsstd::invalid_argumentif 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) == 0orstr.rfind(prefix, 0) == 0(C++20 hasstarts_with()). - Why is my string not empty after calling
clear()?clear()sets size to 0, but the capacity remains. Useshrink_to_fit()if you need to free memory, but it’s not guaranteed.
Related
- Train-Test Split: Purpose, Methods, and Common Mistakes
- PostgreSQL: How to Execute a SQL String
- MS Access Split Form: Put the Datasheet on the Bottom
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Date Validation in Excel: Formula Rules, Examples & SetupTo validate dates in Excel with a formula, select the entry cells, open Data > Data Validation, choose…
- Insert a Row in Excel and Keep FormulasTo insert a row in Excel and keep formulas, select the row heading where the new row should…
- Excel SUMIFS Between Two Dates: Formula and ExamplesTo sum values in Excel between two dates, use SUMIFS with the date range as a criteria range…
- Excel IFS for Blank Cells: Formulas and Common FixesTo make Excel’s IFS function return a result when a cell is blank, test for a blank first:…
- Excel Formulas with Table References: A Complete GuideExcel formulas with table references use structured references like =SUM(Table1[Sales]) instead of cell addresses like =SUM(B2:B100). These references…
- COUNTIF Date Range in Excel: Formulas and ExamplesTo count dates between two limits in Excel, use COUNTIFS, which can test both the start and end…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.