www.gibmonks.com

Main Page




Previous Page
Next Page

[Page 890 (continued)]

18.4. Substrings

Class string provides member function substrm for retrieving a substring from a string. The result is a new string object that is copied from the source string. Figure 18.3 demonstrates substr.

Figure 18.3. Demonstrating string member function substr.
(This item is displayed on pages 890 - 891 in the print version)

 1  // Fig. 18.3: Fig18_03.cpp
 2  // Demonstrating string member function substr.
 3  #include <iostream>
 4  using std::cout;
 5  using std::endl;
 6
 7  #include <string>
 8  using std::string;
 9
10  int main()
11  {
12     string string1( "The airplane landed on time." );
13
14     // retrieve substring "plane" which
15     // begins at subscript 7 and consists of 5 elements
16     cout << string1.substr( 7, 5 ) << endl;
17     return 0;
18  } // end main

  plane



[Page 891]

The program declares and initializes a string on line 12. Line 16 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.


Previous Page
Next Page