Syntax:
#include <string> string& replace( size_type index, size_type num, const string& str ); string& replace( size_type index1, size_type num1, const string& str, size_type index2, size_type num2 ); string& replace( size_type index, size_type num, const Char* str ); string& replace( size_type index, size_type num1, const Char* str, size_type num2 ); string& replace( size_type index, size_type num1, size_type num2, Char ch); string& replace( iterator start, iterator end, const string& str ); string& replace( iterator start, iterator end, const Char* str ); string& replace( iterator start, iterator end, const Char* str, size_type num ); string& replace( iterator start, iterator end, size_type num, Char ch ); string& replace( iterator start, iterator end, input_iterator start2, input_iterator end2 );
The replace method either:
num characters of the current string with characters from str, beginning at index,num1 characters of the current string (starting at index1) with up to num2 characters from str beginning at index2,num characters of the current string with characters from str, beginning at index in str,num1 characters in the current string (beginning at index1) with num2 characters from str beginning at index2,num1 characters in the current string (beginning at index) with num2 copies of ch,start to end with str,start to end with num characters from str,For example, the following code displays the string “They say he carved it himself…find your soul-mate, Homer.”
string s = "They say he carved it himself...from a BIGGER spoon"; string s2 = "find your soul-mate, Homer."; s.replace( 32, s.length() - 32, s2 ); cout << s << endl;
The replace method can be used to replace all occurrences of one string with another.
For example:
string& replaceAll(string& context, const string& from, const string& to) { size_t lookHere = 0; size_t foundHere; while((foundHere = context.find(from, lookHere)) != string::npos) { context.replace(foundHere, from.size(), to); lookHere = foundHere + to.size(); } return context; }
Related Topics: insert