c++string删除指定字符
时间: 2023-12-07 20:42:53 浏览: 1076
在 C++ 中,可以使用字符串操作函数和算法来删除指定字符。以下是一种常见的方法:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "Hello World";
char ch = 'o';
str.erase(std::remove(str.begin(), str.end(), ch), str.end());
std::cout << str << std::endl;
return 0;
}
```
在上面的示例中,我们使用了 `erase` 函数和 `remove` 算法来删除指定字符。首先,我们定义了一个字符串 `str` 和一个字符 `ch`,然后使用 `remove` 函数将要删除的字符移动到字符串的末尾,然后使用 `erase` 函数将末尾的字符删除。最后,我们输出修改后的字符串。
请注意,这种方法只能删除单个字符,并且它会修改原始字符串。如果需要删除多个字符或者不想修改原始字符串,可以使用其他方法,如创建一个新的字符串来保存删除后的结果。
阅读全文
相关推荐













