Step 5 of 6
string search and substrings
std::string has many useful member functions. The two you'll use most for text processing are find and substr:
#include <iostream>
#include <string>
int main() {
std::string email = "ada.lovelace@example.com";
std::size_t at = email.find('@');
std::string user = email.substr(0, at);
std::string domain = email.substr(at + 1);
std::cout << user << " | " << domain << "\n";
std::size_t dot = user.find('.');
std::cout << user.substr(dot + 1) << "\n";
std::cout << (email.find("xyz") == std::string::npos) << "\n";
std::cout << email.rfind('.') << "\n";
}
ada.lovelace | example.com
lovelace
1
20
find
s.find(x) searches for a character or substring and returns the index of the first match. If there's no match it returns the special value std::string::npos (the largest possible size_t). Always check for npos before using the result: using it as a position leads to wrong results or out-of-range errors. rfind searches from the end. Both can take a starting position as a second argument.
substr
s.substr(pos, len) returns a new string of len characters starting at pos. Leave out len to take everything to the end. If pos is beyond the end of the string, it throws an error, so make sure it's valid.
Store find's result as size_t
find returns a std::size_t. Storing it in an int is a bad habit: comparing that int with npos only works through a conversion quirk, the compiler warns about mixing signed and unsigned, and it breaks for very long strings. Use std::size_t (or auto).
Your turn: write std::string map_name(const std::string& s) that strips a prefix ending in the first _. "de_dust2" becomes "dust2"; a string without _ is returned unchanged.