21.5 Swapping strings

Class string provides member function swap for swapping strings. Figure 21.4 swaps two strings. Lines 8–9 declare and initialize strings first and second. Each string is then output. Line 14 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.

Fig. 21.4 Using the swap function to swap two strings.

Alternate View

 1  // Fig. 21.4: Fig21_04.cpp
 2  // Using the swap function to swap two strings.
 3  #include <iostream>
 4  #include <string>
 5  using namespace std;
 6
 7  int main() {
 8     string first{"one"};
 9     string second{"two"};
10
11     // output strings
12     cout << "Before swap:
 first: " << first << "
second: " << second;
13
14     first.swap(second); // swap strings
15
16     cout << "

After swap:
 first: " << first
17        << "
second: " << second << endl;
18  }

Before swap:
 first: one
second: two

After swap:
 first: two
second: one
..................Content has been hidden....................

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