在 C++ 中,如果我们需要将一个 字符串 中的特定字符串替换为另一个字符串,我们可以使用 replace 函数。replace 函数会返回替换后的字符串的 引用。
string& replace (size_t pos, size_t len, const string& str);
参数 | 描述 |
---|---|
pos | 起始位置 |
len | 长度 |
str | 要替换成的字符串 |
返回替换后的字符串的引用。
我们使用了 replace 函数,实现了将字符串中从下标 pos 开始,长度为 len 的字符串替换为 str。
C++ replace 函数字符串替换
#include <iostream>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
string str1 = "I love HaiCoder and i learn C++ from HaiCoder";
string newStr = str1.replace(2, 4, "LIKE");
cout << "str1 = " << str1 << endl;
cout << "newStr = " << newStr << endl;
}
程序运行后,控制台输出如下:
我们首先,定义了一个字符串 变量 str1,接着,我们使用了字符串的 replace 函数,实现了将字符串 str1 中从下标 2 开始,长度为 4 的字符串替换为 LIKE。
这里,即是把 “love” 替换为 LIKE,最后,我们打印 str1 和 replace 函数的返回值,我们发现,字符串 str1 和返回的值都是替换后的字符串。
C++ replace 函数可以使用迭代器
#include <iostream>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
string str1 = "I love HaiCoder and i learn C++ from HaiCoder";
cout << "str1 = " << str1 << endl;
string newStr = str1.replace(str1.begin(), str1.begin()+6, "LIKE");
cout << "newStr = " << newStr << endl;
}
程序运行后,控制台输出如下:
我们可以使用迭代器对字符串进行替换。
C++ replace 函数可以替换指定位置的字符串
#include <iostream>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
string str1 = "I love HaiCoder and i learn C++ from HaiCoder";
string substr="12345";
cout << "str1 = " << str1 << endl;
string newStr = str1.replace(0, 5, substr, substr.find("2"), 3);
cout << "newStr = " << newStr << endl;
}
程序运行后,控制台输出如下:
我们使用 replace 函数可以替换指定位置的字符串。
在 C++ 中,如果我们需要将一个字符串中的特定字符串替换为另一个字符串,我们可以使用 replace 函数。replace 函数会返回替换后的字符串的引用。