stdstring 删除指定字符
要删除字符串中的指定字符,您可以使用 std::string 类的 erase() 函数。
以下是一个示例代码,演示如何删除字符串中的指定字符:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
char ch = 'o';
// 查找字符的位置
size_t pos = str.find(ch);
// 循环删除所有的指定字符
while (pos != std::string::npos) {
// 删除字符
str.erase(pos, 1);
// 继续查找下一个字符的位置
pos = str.find(ch);
}
std::cout << str << std::endl; // 输出:Hell, Wrld!
return 0;
}
在上面的示例中,我们首先使用 find() 函数查找指定字符的位置,然后使用 erase() 函数删除该字符。然后,我们循环查找并删除所有的指定字符,直到没有找到更多的字符。
请注意,std::string 类的 erase() 函数接受两个参数:要删除的字符的位置和要删除的字符的数量。在上面的示例中,我们将要删除的字符的位置传递给 erase() 函数,并将要删除的字符的数量设置为 1,以删除单个字符。
希望对您有所帮助
原文地址: https://www.cveoy.top/t/topic/iafR 著作权归作者所有。请勿转载和采集!