Text is part of nearly every program: names, messages, commands typed by a user, lines read from a file. In modern C++, text is stored in std::string, a class from the standard library that manages its own memory and grows as needed. You met it briefly in the variables lesson; this lesson shows what it can really do.
A std::string behaves like a sequence of char values. You can read any character by its position, take out a piece with substr, search with find and change the text in place with insert, erase and replace. Unlike strings in Java or Python, a C++ string is mutable: these member functions change the string itself.
By the end of this lesson you'll be able to clean up input, pull information out of text, compare words and convert between text and numbers, which covers most of the string work beginners need.
Creating strings, length and characters
#include <string>
using namespace std;
string word = "Keyboard";
word.size(); // 8 (length() means the same)
word[0]; // 'K'
word.back(); // 'd'
word += "s"; // "Keyboards"- Include
<string>to usestd::string. - Positions start at 0; the last character is at
size() - 1. []doesn't check the position;word.at(20)does and throwsstd::out_of_rangeif it's invalid.+and+=join strings. You can join astringwith a text literal, but not two literals:"Hi" + " there"won't compile.
Substrings and searching
| Member function | What it does |
|---|---|
s.substr(pos, len) | A new string of len characters from pos |
s.find("abc") | Position of the first match |
s.rfind("abc") | Position of the last match |
s.find('x', start) | Search starting at a position |
s.empty() | true if there are no characters |
When find doesn't find anything, it returns the special value string::npos, not -1. Always compare with it: if (s.find("@") != string::npos). Leaving out len in substr takes everything to the end of the string.
Changing a string
Because std::string is mutable, these functions modify the string they're called on:
string s = "Hello world";
s.insert(5, ","); // "Hello, world"
s.erase(0, 7); // "world"
s.replace(0, 1, "W"); // "World"
s.push_back('!'); // "World!"erase(pos, len) removes len characters starting at pos, and replace(pos, len, text) swaps that part for new text. To change every character, loop with a reference: for (char& c : s) c = toupper(c);, using functions from <cctype> such as toupper, tolower, isdigit and isspace.
Comparing and converting
==, !=, < and > compare strings by their characters, so "apple" < "banana" is true. Comparison is case-sensitive, and capital letters sort before lower-case ones.
To convert between text and numbers:
| Function | Example | Result |
|---|---|---|
stoi(s) | stoi("42") | 42 (int) |
stod(s) | stod("3.5") | 3.5 (double) |
to_string(n) | to_string(7) | "7" |
stoi throws std::invalid_argument if the text doesn't start with a number, which you'll learn to handle in later lessons.
Escape sequences and raw strings
Some characters can't be typed directly between double quotes, so C++ uses escape sequences that start with a backslash:
| Write | You get |
|---|---|
\n | New line |
\t | Tab |
\" | A double quote inside a string |
\' | A single quote, needed in a char like '\'' |
\\ | One backslash |
Backslashes get awkward in Windows paths and patterns, where every \ must be doubled: "C:\\Users\\ana". A raw string literal switches escapes off. Everything between R"( and )" is taken exactly as written:
string path = R"(C:\Users\ana\notes.txt)";
string quote = R"(She said "hi")";If the text itself contains )", add a few letters of your choice on both sides, such as R"x(say "(hi)")x"; the string then ends only at )x".
Remember too that a char and a string are different types. 'a' is a single character, and "a" is a string holding one character. You can add a char to a string with + or push_back, but you can't compare 'a' == "a".
C++ Strings Syntax
String operations
#include <string>
string s = "text";
s.size(); s[0]; s.at(0);
s.substr(pos, len);
s.find("x") != string::npos;
s.insert(pos, "x"); s.erase(pos, len); s.replace(pos, len, "x");
int n = stoi("42"); string t = to_string(n);C++ Strings Summary
std::stringfrom<string>stores text and grows automatically.- Index with
s[i]or the checkeds.at(i);size()gives the length. substr,findandrfindread and search;findreturnsstring::nposwhen nothing is found.insert,erase,replaceand+=change the string itself.- Compare with
==and<; convert withstoi,stodandto_string.
C++ Strings Examples
Each example shows the code, the output it produces and what each part does.
Splitting an email address
#include <iostream>
#include <string>
using namespace std;
int main() {
string email = "maya.patel@example.com";
size_t at = email.find('@');
if (at == string::npos) {
cout << "Not an email" << endl;
return 0;
}
string user = email.substr(0, at);
string domain = email.substr(at + 1);
cout << "User: " << user << endl;
cout << "Domain: " << domain << endl;
cout << "Length: " << email.size() << endl;
return 0;
}User: maya.patel
Domain: example.com
Length: 22Line-by-line explanation
- Line 7find returns the position of '@', stored in a size_t (an unsigned size type).
- Line 9Always check for npos before using the position.
- Lines 13 to 14Everything before the @ is the user, everything after it the domain.
Cleaning and capitalising
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string name = " ada lovelace ";
name.erase(0, name.find_first_not_of(' '));
name.erase(name.find_last_not_of(' ') + 1);
bool newWord = true;
for (char& c : name) {
if (newWord && isalpha(c)) c = toupper(c);
newWord = (c == ' ');
}
cout << "[" << name << "]" << endl;
return 0;
}[Ada Lovelace]Line-by-line explanation
- Line 9Erase everything before the first non-space character.
- Line 10Erase everything after the last non-space character.
- Lines 13 to 16char& lets the loop change each character; letters after a space become capitals.
Numbers inside text
#include <iostream>
#include <string>
using namespace std;
int main() {
string order = "qty=3;price=4.50";
int qty = stoi(order.substr(order.find('=') + 1));
double price = stod(order.substr(order.rfind('=') + 1));
double total = qty * price;
string label = "Total: " + to_string(total);
cout << label << endl;
cout << (string("apple") < string("banana")) << endl;
return 0;
}Total: 13.500000
1Line-by-line explanation
- Line 8stoi reads digits until it reaches a character that isn't part of a number, so it stops at the ;.
- Line 9rfind finds the last '=', then stod reads the price.
- Line 12to_string uses six decimal places for doubles; use a stream or printf for nicer formatting.
- Line 14Comparison is alphabetical, and cout prints true as 1.
Common C++ Strings Mistakes
Comparing find with -1
if (s.find("x") == -1) { ... }if (s.find("x") == string::npos) { ... }npos is a very large unsigned number. Comparing with npos is the correct, portable test.
Adding two text literals
string greeting = "Hello, " + "world"; // error: two char arraysstring greeting = string("Hello, ") + "world";Reading past the end with []
string s = "abc";
cout << s[10]; // undefined behaviourstring s = "abc";
cout << s.at(10); // throws std::out_of_range, which you can catchC++ Strings in Real Projects
Strings in C++ programs
Game engines parse configuration and level files line by line, command-line tools split the arguments you type, and network programs build and read text messages. High-performance code also uses std::string_view, a read-only view of existing text that avoids copying, once you're comfortable with std::string.
C++ Strings FAQ
How do I split a string by a delimiter in C++?
Put the string into an istringstream from <sstream> and call getline with the delimiter as its third argument: while (getline(in, part, ',')) parts.push_back(part);. Each call reads up to the next comma. The formatting lesson shows this with a full CSV line.
How do I reverse a string in C++?
Include <algorithm> and call reverse(s.begin(), s.end());, which reverses the string in place, so "stressed" becomes "desserts". To keep the string as it was, build a reversed copy instead: string r(s.rbegin(), s.rend());.
How do I check if a string starts or ends with some text?
In C++20, use s.starts_with("rep") and s.ends_with(".pdf"), which both return a bool. With older compilers, s.rfind("rep", 0) == 0 tests the start, and comparing the last few characters with substr tests the end. Both checks are case-sensitive.
What is the difference between std::string and a char array?
A C-style string like char name[] = "hi"; is a fixed-size array that ends with a hidden '\0' character, so it's 3 bytes long, and you need functions such as strlen and strcpy to work with it. std::string manages its own memory, grows automatically and supports +, == and size(). Use std::string, and call s.c_str() when an older function needs a C-style string.
Why does to_string(3.5) give "3.500000"?
to_string formats a double with exactly six decimal places, whatever the value. To control the decimals, format with an ostringstream and setprecision, or with std::format("{:.2f}", x) in C++20, both covered in the formatting lesson. For whole numbers, to_string gives exactly the digits you expect.
C++ Strings Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the code so it prints the number of characters in city.
string city = "Lisbon";
cout << city.();
What does this print?
string s = "Computer";
cout << s.substr(3, 3);
What does this print?
string s = "banana";
s.replace(0, 1, "B");
s.erase(3);
cout << s;
What does find return when the text isn't found?
What does this print?
cout << stoi("42abc") + 1;
C++ Strings Quiz
5 questions to check what you learned.
Which header do you include for std::string?
- <iostream>
- <text>
- <string>
- <cstring>
How does
s.at(i)differ froms[i]?- There's no difference
- at() checks the position and throws an exception if it's invalid
- at() returns a copy, [] returns a reference
- [] only works on const strings
Are C++ std::string objects mutable?
- No, every change creates a new string
- Only if declared mutable
- Only with pointers
- Yes, functions like insert and erase change the string itself
Which function turns the number 15 into the text "15"?
- stoi(15)
- string(15)
- to_string(15)
- str(15)
Why is
"Hi" + " there"an error?- Strings can't contain spaces
- Both are character array literals, and + isn't defined for two of them
- + only joins numbers
- You must use append()