.NODE

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 
 4 using std::cout;
 5 using std::endl;
 6
 7 #include 
 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:
 first: " << first << "
second: " << second;
17
18 first.swap( second ); // swap strings
19
20 cout << "

After swap:
 first: " << first
21 << "
second: " << 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.

Introduction to Computers, the Internet and World Wide Web

Introduction to C++ Programming

Introduction to Classes and Objects

Control Statements: Part 1

Control Statements: Part 2

Functions and an Introduction to Recursion

Arrays and Vectors

Pointers and Pointer-Based Strings

Classes: A Deeper Look, Part 1

Classes: A Deeper Look, Part 2

Operator Overloading; String and Array Objects

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

Templates

Stream Input/Output

Exception Handling

File Processing

Class string and String Stream Processing

Web Programming

Searching and Sorting

Data Structures

Bits, Characters, C-Strings and structs

Standard Template Library (STL)

Other Topics

Appendix A. Operator Precedence and Associativity Chart

Appendix B. ASCII Character Set

Appendix C. Fundamental Types

Appendix D. Number Systems

Appendix E. C Legacy Code Topics

Appendix F. Preprocessor

Appendix G. ATM Case Study Code

Appendix H. UML 2: Additional Diagram Types

Appendix I. C++ Internet and Web Resources

Appendix J. Introduction to XHTML

Appendix K. XHTML Special Characters

Appendix L. Using the Visual Studio .NET Debugger

Appendix M. Using the GNU C++ Debugger

Bibliography

show all menu





C++ How to Program
C++ How to Program (5th Edition)
ISBN: 0131857576
EAN: 2147483647
Year: 2004
Pages: 627
Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net