写一段c++代码实现删除一段字符串中的固定字符
以下是一个简单的 C++ 代码示例,用于删除字符串中指定的字符:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Hello, World!";
char ch = 'o';
// 删除指定字符
str.erase(remove(str.begin(), str.end(), ch), str.end());
cout << str << endl;
return 0;
}
在这个示例中,我们定义了一个字符串 str 和一个要删除的字符 ch。我们使用 std::remove() 函数和 std::string::erase() 函数来删除指定的字符。
std::remove() 函数会将字符串中所有等于指定字符的元素移动到数组的末尾,并返回一个指向新的逻辑结尾的迭代器。std::string::erase() 函数则将从新的逻辑结尾到字符串末尾的所有元素删除。
这段代码将输出 Hell, Wrld!。
原文地址: https://www.cveoy.top/t/topic/Gxv 著作权归作者所有。请勿转载和采集!