The replace() Function

◀ The assign() Function▶ The find() Function
Amazon You can replace a substring of a string with a given string or char array by using the replace() function! There is a variety of the replace() function constructors and I will just show you the most useful ones.

Here are their prototypes:
string & replace(int pos, int n, const string & s);
string & replace(int pos, int n, const char* cs);
string & replace(int pos, int n, const char* cs, int n2, int n3);
string & replace(int pos, int n, int n2, char c);
The first function replaces with s from index pos spanning n characters of the invoking string. The second one replaces with cs contents from index pos spanning n characters.


The third one replaces content from index pos spanning n characters with the first n3 characters of cs starting at n2. The fourth one replaces content from index pos spanning n characters with n2 c’s. Here are several examples:
string a = "Best Worst";
string b = "wishes to Demon";
char *c = "Lali";
char *c2 = "Dell";
char d = '~';
a.replace(5, 5, b);  /* a is "Best wishes to Demon" */
a.replace(15, 5, c);  /* a is "Best wishes to Lali" */
a.replace(15, 1, c2, 0, 1); /* a is "Best wishes to Dali" */ a.replace(19, 0, 3, d); /* a is "Best wishes to Dali~~~" */
This function may come in handy in some situation so make sure you know it!

Next let’s look at how we can locate a string in another string!
◀ The assign() Function▶ The find() Function

fShare
Questions? Let me know!