Skip to main content

Section 9.10 Substrings

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:
string substr (size_t pos = 0, size_t len = npos) const;
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:
Listing 9.10.1.
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.

Insight 9.10.1.

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).
If you set an invalid pos for substr start from, a run time error will be generated (try setting one of the find’s above to start from 1000).
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:
Listing 9.10.2.

Checkpoint 9.10.1.

Given the string declaration: string s = "football team", which is the correct way to copy the string "ball" from it?
  • s.substr(5)
  • We need to specify a length
  • s.substr(5, 9)
  • The second parameter is the length, not the end index
  • s.substr('b', 4)
  • The first parameter is the index, not the character
  • s.substr(5, 4)
  • Yes, we want to start at 5 and copy 4 characters

Checkpoint 9.10.2.

Given the string declaration: string s = "football team", which are correct ways to copy the string "team" from it?
  • s.substr(9)
  • Yes, we can start at 9 and copy the rest of the string
  • s.substr(9, 4)
  • Yes, we can start at 9 and copy 4 characters
  • s.substr(-4)
  • We can’t use negative indexes in C++ (some languages allow that)
You have attempted of activities on this page.