替换(replace)
语法:
basic_string &replace( size_type index, size_type num, const basic_string &str ); basic_string &replace( size_type index1, size_type num1, const basic_string &str, size_type index2, size_type num2 ); basic_string &replace( size_type index, size_type num, const char *str ); basic_string &replace( size_type index, size_type num1, const char *str, size_type num2 ); basic_string &replace( size_type index, size_type num1, size_type num2, char ch ); basic_string &replace( iterator start, iterator end, const basic_string &str ); basic_string &replace( iterator start, iterator end, const char *str ); basic_string &replace( iterator start, iterator end, const char *str, size_type num ); basic_string &replace( iterator start, iterator end, size_type num, char ch ); |
replace()函数:
- 用str中的num个字符替换本字符串中的字符,从index开始
- 用str中的num2个字符(从index2开始)替换本字符串中的字符,从index1开始,最多num1个字符
- 用str中的num个字符(从index开始)替换本字符串中的字符
- 用str中的num2个字符(从index2开始)替换本字符串中的字符,从index1开始,num1个字符
- 用num2个ch字符替换本字符串中的字符,从index开始
- 用str中的字符替换本字符串中的字符,迭代器start和end指示范围
- 用str中的num个字符替换本字符串中的内容,迭代器start和end指示范围,
- 用num个ch字符替换本字符串中的内容,迭代器start和end指示范围.
例如,以下代码显示字符串"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, s2.length(), s2 ); cout << s << endl;