string去掉特定字符串
时间: 2023-08-22 22:07:52 浏览: 99
要去除一个字符串中的特定字符串,可以使用string的replace()函数。具体步骤如下:
1. 定义一个字符串变量str,存储原始字符串。
2. 定义一个要去除的字符串变量sub_str,存储要去除的特定字符串。
3. 使用replace()函数,将str中的sub_str替换为空字符串。
4. 最终得到的字符串即为去除特定字符串后的结果。
以下是一个示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "this is a test string. test is to be removed.";
string sub_str = "test";
string result = str;
// 使用replace函数去除特定字符串
size_t pos = 0;
while ((pos = result.find(sub_str, pos)) != string::npos) {
result.replace(pos, sub_str.length(), "");
pos += 1;
}
cout << "Original string: " << str << endl;
cout << "Sub-string to be removed: " << sub_str << endl;
cout << "Result string: " << result << endl;
return 0;
}
```
输出结果为:
```
Original string: this is a test string. test is to be removed.
Sub-string to be removed: test
Result string: this is a string. is to be removed.
```
阅读全文