Friday, August 26, 2011

Strings 101 - Part IV


The string insert() method.

This method allows you to insert one string inside another. There are many versions of this method but we'll only use two of them.

The following program illustrates how to insert one string s1, into another s2.

Example 1
string s1 = " hello ";
string s2 = "123456789";

string s3 = s2.insert(3, s1);

cout << s3 << endl;

This program prints the following:


Notice from the output that the string s1, "hello" is inserted inside the string s2, "123456789" so that s3 becomes "123hello456789"

Here's another example, in this case, we're using a different version of the insert() method. This one inserts a single character a number of times into a string.

Example 2:
string s1 = "123456789";
char c = 'x';

string s3 = s1.insert(3,10,c);

cout << s3 << endl;

This one prints the following:


Notice that the output this time is "123xxxxxxxxxx456789". The character 'x' was inserted at position 3 into the string s1.