www.gibmonks.com

Main Page




Previous Page
Next Page

[Page 891 (continued)]

18.5. Swapping strings

Class string provides member function swap for swapping strings. Figure 18.4 swaps two strings.

Figure 18.4. Using function swap to swap two strings.

 1  // Fig. 18.4: Fig18_04.cpp
 2  // Using the swap function to swap two strings.
 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 first( "one" );
13     string second( "two" );
14
15     // output strings
16     cout << "Before swap:\n first: " << first << "\nsecond: " << second;
17
18     first.swap( second ); // swap strings
19
20     cout << "\n\nAfter swap:\n first: " << first
21        << "\nsecond: " << second << endl;
22     return 0;
23  } // end main

 Before swap:
  first: one
 second: two

 After swap:
  first: two
 second: one


Lines 1213 declare and initialize strings first and second. Each string is then output. Line 18 uses string member function swap to swap the values of first and second. The two strings are printed again to confirm that they were indeed swapped. The string member function swap is useful for implementing programs that sort strings.


Previous Page
Next Page