19.9. Inserting Characters into a string

Class string provides member functions for inserting characters into a string. Figure 19.8 demonstrates the string insert capabilities.


 1   // Fig. 19.8: Fig19_08.cpp
 2   // Demonstrating class string insert member functions.
 3   #include <iostream>
 4   #include <string>
 5   using namespace std;
 6
 7   int main()
 8   {
 9      string string1( "beginning end" );
10      string string2( "middle " );
11      string string3( "12345678" );
12      string string4( "xx" );
13
14      cout << "Initial strings: string1: " << string1
15         << " string2: " << string2 << " string3: " << string3
16         << " string4: " << string4 << " ";
17
18      // insert "middle" at location 10 in string1
19      string1.insert( 10, string2 );              
20
21      // insert "xx" at location 3 in string3       
22      string3.insert( 3, string4, 0, string::npos );
23
24      cout << "Strings after insert: string1: " << string1
25         << " string2: " << string2 << " string3: " << string3
26         << " string4: " << string4 << endl;
27   } // end main


Initial strings:
string1: beginning end
string2: middle
string3: 12345678
string4: xx

Strings after insert:
string1: beginning middle end
string2: middle
string3: 123xx45678
string4: xx


Fig. 19.8. Demonstrating class string insert member functions.

The program declares, initializes then outputs strings string1, string2, string3 and string4. Line 19 uses string member function insert to insert string2’s content before element 10 of string1.

Line 22 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.

..................Content has been hidden....................

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