The std::string methods that handle everyday text are a short list that you will use constantly. You find a substring, you take a piece of one, you replace part of one, you remove characters, you insert text, and you compare and convert between types. These cover the vast majority of the text processing that application code actually does.
The previous lesson in this module covered "What Is the Difference Between C-Strings and std::string?", and the next lesson in this module is about "How Do Multidimensional Arrays Work in C++?".
Finding text
The method find() searches for a substring and it gives back the position of the first match, or std::string::npos if there is none.
#include <iostream>
#include <string>
int main() {
std::string title = "The Silent Shelf";
std::size_t first = title.find("Shelf");
std::cout << "first: " << first << '\n';
if (first != std::string::npos) {
std::cout << "found: " << title.substr(first) << '\n';
} else {
std::cout << "not found\n";
}
std::cout << "rfind: " << title.rfind("e") << '\n';
std::cout << "missing: " << (title.find("Zebra") == std::string::npos) << '\n';
return 0;
}The output shows the first match, the last match, and the safe way to test for absence.
first: 11
found: Shelf
rfind: 13
missing: 1Taking a piece
The method substr() gives back a new string that starts at a position, with an optional length.
#include <iostream>
#include <string>
int main() {
std::string line = "ISBN: 978-1-4028-9462-6";
std::string label = line.substr(0, 4);
std::string digits = line.substr(5);
std::cout << "label: " << label << '\n';
std::cout << "digits: " << digits << '\n';
std::cout << "isbn: " << line.substr(5, 3) << '\n';
return 0;
}The output shows the three substrings.
label: ISBN
digits: 978-1-4028-9462-6
isbn: 97Replacing, erasing and inserting
The method insert() puts new text at a position.
#include <iostream>
#include <string>
int main() {
std::string title = "The Silent Shelf";
title.replace(4, 6, "Golden");
std::cout << "replaced: " << title << '\n';
title.erase(0, 4);
std::cout << "erased: " << title << '\n';
title.insert(0, "Shelf: ");
std::cout << "inserted:" << title << '\n';
return 0;
}The output shows each of the edits applied in turn.
replaced: The Golden Shelf
erased: Golden Shelf
inserted:Shelf: Golden ShelfComparing and converting
For the conversion, std::stoi and std::stod parse a number out of a string, and they throw std::invalid_argument when the text is not a number at all.
#include <iostream>
#include <string>
int main() {
std::string pages_text = "342";
int pages = std::stoi(pages_text);
std::cout << "pages: " << pages << '\n';
std::string price_text = "12.50";
double price = std::stod(price_text);
std::cout << "price: " << price << '\n';
std::string a = "apple";
std::string b = "apricot";
std::cout << "compare: " << a.compare(b) << '\n';
std::cout << "equal?: " << (a == std::string("apple")) << '\n';
return 0;
}The output shows the parsed numbers and the comparison result.
pages: 342
price: 12.5
compare: -2
equal?: 1Trimming and cleaning text
To trim the whitespace, you find the first and the last non-space characters and you take the substring between them.
#include <iostream>
#include <string>
std::string trim(const std::string& text) {
const std::string spaces = " \t\n\r";
std::size_t start = text.find_first_not_of(spaces);
if (start == std::string::npos) {
return "";
}
std::size_t end = text.find_last_not_of(spaces);
return text.substr(start, end - start + 1);
}
int main() {
std::string padded = " The Silent Shelf ";
std::cout << "trimmed: [" << trim(padded) << "]\n";
std::string shout;
for (char c : padded) {
shout += static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
}
std::cout << "upper: " << trim(shout) << '\n';
return 0;
}The output shows both the trimming and the case change.
trimmed: [The Silent Shelf]
upper: THE SILENT SHELFIterating over a string
A std::string behaves like a sequence of characters, so it can be walked with a range-based for loop or with the standard algorithms.
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
int main() {
std::string title = "Fiction";
std::cout << "characters: ";
for (char c : title) {
std::cout << c << '.';
}
std::cout << '\n';
int vowels = 0;
for (char c : title) {
if (std::string("aeiou").find(c) != std::string::npos) {
++vowels;
}
}
std::cout << "vowels: " << vowels << '\n';
std::string upper = title;
std::transform(upper.begin(), upper.end(), upper.begin(),
[](unsigned char c) { return static_cast<char>(std::toupper(c)); });
std::cout << "upper: " << upper << '\n';
return 0;
}The output shows all three of the results.
characters: F.i.c.t.i.o.n.
vowels: 3
upper: FICTIONThe everyday checklist
find()andrfind()locate text, and they give backstd::string::nposwhen there is no match.substr()takes a piece, and it always gives back a new string.replace(),erase()andinsert()change the text in place.std::stoiandstd::stodturn text into a number, and they throw when the text is not one.compare()and the equality operators compare the contents, and not the addresses.find_first_not_ofandfind_last_not_oftrim the whitespace.
Quick reference
findgives back the first position, andnposmeans that there is no match.substrtakes a piece without changing the original.replace,eraseandinsertchange the string in place.stoiandstodparse a number, and they throw on bad text.comparegives back a negative number, a zero or a positive number.- Always check for
nposbefore you use a position that came fromfind.
Try it yourself: write a program that takes a title of a book and finds the year in it, trims the whitespace from both ends, and prints the title in upper case. Then make the program handle the case where there is no year, and confirm that it does not try to use a position of npos as if it were a real one.