21.4 Substrings

Class string provides member function substr for retrieving a substring from a string. The result is a new string object that’s copied from the source string. Figure 21.3 demonstrates substr. The program declares and initializes a string at line 8. Line 12 uses member function substr to retrieve a substring from string1. The first argument specifies the beginning subscript of the desired substring; the second argument specifies the substring’s length.

Fig. 21.3 Demonstrating string member function substr.

Alternate View

 1  // Fig. 21.3: Fig21_03.cpp
 2  // Demonstrating string member function substr.
 3  #include <iostream>
 4  #include <string>
 5  using namespace std;
 6
 7  int main() {
 8     string string1{"The airplane landed on time."};
 9
10     // retrieve substring "plane" which
11     // begins at subscript 7 and consists of 5 characters
12     cout << string1.substr(7, 5) << endl;
13   }

plane
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset