字符串常用函数之替换函数replace()的基本用法(C++少儿编程|信息学奥赛)
作者:野牛程序员:2023-06-20 09:00:53C++程序设计阅读 3138
在C++中,字符串类提供了一个名为replace()的成员函数,用于替换字符串中的指定部分。
replace()函数的基本用法如下:
string replace(const string& str, const string& old_substr, const string& new_substr);
其中,str是要进行替换操作的原始字符串,old_substr是要被替换的子字符串,new_substr是用来替换旧子字符串的新子字符串。
replace()函数返回一个新的字符串,它是将str中的所有old_substr都替换为new_substr后得到的结果。
下面是一个使用replace()函数的示例:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::string old_substr = "World";
std::string new_substr = "C++";
std::string replaced_str = str.replace(str.find(old_substr), old_substr.length(), new_substr);
std::cout << replaced_str << std::endl;
return 0;
}在上面的示例中,原始字符串str是"Hello, World!",要替换的子字符串old_substr是"World",新子字符串new_substr是"C++"。
使用str.find(old_substr)可以找到old_substr在str中第一次出现的位置。然后,old_substr.length()用于指定要替换的子字符串的长度。
replace()函数的结果被存储在replaced_str中,并输出到控制台上。最终的输出结果是"Hello, C++!"。
请注意,replace()函数并不会修改原始字符串str,而是返回一个新的字符串作为替换结果。如果需要修改原始字符串,可以使用赋值操作符或者调用str.replace()函数来实现。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

