Class string provides member functions for inserting characters into a string. Figure 18.8 demonstrates the string insert capabilities.
Figure 18.8. Demonstrating the string insert member functions.
(This item is displayed on pages 898 - 899 in the print version)
1 // Fig. 18.8: Fig18_08.cpp 2 // Demonstrating class string insert member functions. 3 #include 4 using std::cout; 5 using std::endl; 6 7 #include 8 using std::string; 9 10 int main() 11 { 12 string string1( "beginning end" ); 13 string string2( "middle " ); 14 string string3( "12345678" ); 15 string string4( "xx" ); 16 17 cout << "Initial strings: string1: " << string1 18 << " string2: " << string2 << " string3: " << string3 19 << " string4: " << string4 << " "; 20 21 // insert "middle" at location 10 in string1 22 string1.insert( 10, string2 ); 23 24 // insert "xx" at location 3 in string3 25 string3.insert( 3, string4, 0, string::npos ); 26 27 cout << "Strings after insert: string1: " << string1 28 << " string2: " << string2 << " string3: " << string3 29 << " string4: " << string4 << endl; 30 return 0; 31 } // end main
|
The program declares, initializes and then outputs strings string1, string2, string3 and string4. Line 22 uses string member function insert to insert string2's content before element 10 of string1.
Line 25 uses insert to insert string4 before string3's element 3. The last two arguments specify the starting and last element of string4 that should be inserted. Using string::npos causes the entire string to be inserted.
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