The insert() Function
◀ The substr() Function▶ The assign() Function Amazon
The
insert() functions allow you to insert a character, a character array, a string, or multiple characters into a string, given the starting position. Here are the prototypes of the most commonly used
insert() functions:
string & insert(int pos, const string & s);
string & insert(int pos, const char *cs);
string & insert(int pos, const char *cs, int n);
string & insert(int pos, int n, char c);
The first function inserts
s in the invoking object at index
pos. The second one inserts
cs in the invoking object at index
pos. The third one inserts the first
n characters in
cs in the invoking object at index
pos. The fourth one inserts
n’s
c in the invoking object at index
pos. Here are several examples:
string a = "Petrina ";
string b = "dogs";
char *c = "loves cats";
char d = '.';
a.insert(8, b); /* a is "Petrina dogs" */
a.insert(8, c, 6); /* a is "Petrina loves dogs" */
a.insert(7, 3, d); /* a is "Petrina... loves dogs" */
Inserting a string in another string may not be common but it’s still good to know. Next let’s look at
assign() function!
◀ The substr() Function▶ The assign() Function