C++ Strings
A string is a sequence of characters. Modern C++ uses the std::string class from the <string> header. Unlike the raw character arrays of C, a std::string knows its own length, grows automatically and cleans up its memory for you.
Creating and joining strings
Use + to concatenate (join) strings, or += to append to an existing one:
#include <iostream>
#include <string>
using namespace std;
int main() {
string first = "Grace";
string last = "Hopper";
string full = first + " " + last;
cout << full << "\n";
string greeting = "Hi";
greeting += ", ";
greeting += full;
greeting += '!';
cout << greeting << "\n";
}Grace Hopper
Hi, Grace Hopper!
Note: You cannot add two string literals directly:
"a" + "b"does not compile, because literals are plain character arrays. At least one side of+must be astd::string.
Length and individual characters
size() (or its synonym length()) returns the number of characters. Characters are numbered from 0; access them with [] or the bounds-checked at():
#include <iostream>
#include <string>
using namespace std;
int main() {
string word = "planet";
cout << "Length: " << word.size() << "\n";
cout << "First: " << word[0] << "\n";
cout << "Last: " << word[word.size() - 1] << "\n";
cout << "Also last: " << word.back() << "\n";
word[0] = 'P';
cout << word << "\n";
}Length: 6
First: p
Last: t
Also last: t
Planet
word[10] on a 6-character string is undefined behaviour, while word.at(10) throws an exception you can catch — useful while learning.
Useful member functions
| Function | What it does |
|---|---|
s.substr(pos, len) |
Copy of len characters starting at pos |
s.find(text) |
Index of the first match, or string::npos |
s.replace(pos, len, text) |
Replace a range with other text |
s.insert(pos, text) |
Insert text before pos |
s.erase(pos, len) |
Remove characters |
s.empty() |
true if the string has no characters |
s.starts_with(x) / s.ends_with(x) |
Prefix / suffix test (C++20) |
#include <iostream>
#include <string>
using namespace std;
int main() {
string email = "lin.chen@example.org";
size_t at = email.find('@');
string user = email.substr(0, at);
string domain = email.substr(at + 1);
cout << "User: " << user << "\n";
cout << "Domain: " << domain << "\n";
cout << boolalpha << domain.ends_with(".org") << "\n";
if (email.find("gmail") == string::npos) {
cout << "Not a gmail address\n";
}
}User: lin.chen
Domain: example.org
true
Not a gmail address
Numbers and strings
Convert a number to text with to_string, and text to a number with stoi (int) or stod (double):
#include <iostream>
#include <string>
using namespace std;
int main() {
int year = 2024;
string label = "Year " + to_string(year);
cout << label << "\n";
string qty = "42";
string price = "3.5";
cout << stoi(qty) * stod(price) << "\n";
}Year 2024
147
Looping over characters
A range-based for visits every character. Here we count vowels and build an upper-case copy using toupper from <cctype>:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string text = "Hello World";
int vowels = 0;
string upper;
for (char c : text) {
char lower = tolower(c);
if (lower == 'a' || lower == 'e' || lower == 'i' || lower == 'o' || lower == 'u') {
vowels++;
}
upper += toupper(c);
}
cout << vowels << " vowels\n" << upper << "\n";
}3 vowels
HELLO WORLD
Test yourself
What does string("banana").find("na") return?
- 1
- 2
- 4
- string::npos
Which line does NOT compile?
- string s = "a" + string("b");
- string s = "a" + "b";
- string s = "a"; s += "b";
- string s = string("a") + 'b';
Which function converts the string "15" to the int 15?
- to_string
- stoi
- atoi_s
- int.parse