String Functions
A lot of work with text is finding a part of it and cutting it out. For example, you may want the user name from an email address, which is everything before the @. Two string functions do this together: find and substr.
#include <iostream>
#include <string>
using namespace std;
int main() {
string email = "[email protected]";
int at = email.find("@");
cout << at << "\n";
cout << email.substr(0, at) << "\n";
cout << email.substr(at + 1) << "\n";
return 0;
}
Output:
5
alice
example.com
find(text) gives the index where text first appears. The @ is at index 5, because indexes start at 0 (a is 0, l is 1, and so on).
substr(start, count) gives a new string, a copy of part of the old one. It starts at index start and takes count characters. email.substr(0, at) starts at index 0 and takes 5 characters, which gives alice. If you leave out the count, you get everything from start to the end. That is how email.substr(at + 1) gives the part after the @.
When find does not find it
If the text is not in the string, find returns a special value called string::npos ("no position"). It is a very large number:
string email = "[email protected]";
cout << email.find("#") << "\n";
if (email.find("#") == string::npos) {
cout << "No # in the email" << "\n";
}
Output:
18446744073709551615
No # in the email
Do not use that number directly. If you store the result in an int, as in the first example, it prints as -1 instead. Either way, compare the result of find with string::npos, as the if above does. This is the usual way to check if a string contains some text.
Numbers and text
Text and numbers are different types, even when the text is made of digits. stoi ("string to int") turns text into an int, so you can do math with it. to_string does the opposite: it turns a number into a string, so you can join it with other text.
string age = "42";
cout << stoi(age) + 8 << "\n";
string label = to_string(99) + "%";
cout << label << "\n";
Output:
50
99%
stoi(age) + 8 is 50, a real addition. to_string(99) is the text "99", so + "%" joins the two strings into 99%.
In the exercise, the program reads a line of text and already finds its first space. Use substr to cut out the first word, which is everything before that space.