In addition to searching strings, we often need to extract parts of strings. The substr function returns a new string that copies characters from an existing string. Itβs prototype is:
pos is the index (position) to start from. len is the maximum number of characters to copy. Notice that both parameters are optional. Saying myString.substr() is the same as myString.substr(0, string::npos) which says βstart from the beginning and have no maximum number to copyβ. Here are some sample uses of substr:
Note that the original string is not changed. substr just copies parts of it, and does not remove them from the original string. Also note that even if we ask for just one character, the value is returned as a single character string. Not as a char.
If you want to get the one character at position x from a string as a char, use s.at(x). If you want to work with the single character as a string, use s.find(x, 1).
It is common to combine find and substr to chop up strings. This simple program breaks up an email address into the mailbox name and the domain. Notice that if something we find is at index x, then asking for substr(0, x) copies everything up to but not including that item: