Inserting Characters into a string
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.