EducoderC++字符串替换
时间: 2023-07-06 11:36:10 浏览: 51
在 C++ 中,可以使用字符串的 replace() 函数来进行字符串替换。replace() 函数的用法如下:
```cpp
string replace (size_t pos, size_t len, const string& str);
```
其中,pos 表示要替换的位置,len 表示要替换的字符数,str 表示替换后的字符串。
例如,将字符串中的所有 "old" 替换成 "new",可以使用以下代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "old string";
string old_str = "old";
string new_str = "new";
size_t pos = 0;
while ((pos = str.find(old_str, pos)) != string::npos)
{
str.replace(pos, old_str.length(), new_str);
pos += new_str.length();
}
cout << str << endl;
return 0;
}
```
输出结果为:
```
new string
```
在这个例子中,find() 函数用来查找字符串 "old" 在原字符串中的位置,如果找到了就用 replace() 函数进行替换,直到字符串中没有 "old" 为止。