C++ std::string: 删除指定字符 - 高效方法及示例代码
C++ std::string: 删除指定字符 - 高效方法及示例代码
在 C++ 中,你可以使用 std::string 的 erase 函数来删除字符串中的指定字符。以下是一个简单的示例代码,展示了如何删除字符串中所有出现的 'o' 字符:
#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;
return 0;
}
代码解析:
- 首先,我们定义一个字符串
str和一个要删除的字符ch。 - 使用
find函数查找字符ch在字符串中的位置,并存储在pos变量中。 - 如果找到字符
ch(pos != std::string::npos),则使用erase函数删除该字符,并再次使用find函数查找下一个字符ch的位置,继续循环。 - 当
find函数不再找到字符ch时,循环结束,输出修改后的字符串。
代码输出结果:
Hell, Wrld!
总结:
通过以上示例代码,我们学会了使用 erase 函数删除 std::string 中的指定字符。你可以根据需要修改代码中的字符 ch 和字符串 str 来删除不同的字符。
原文地址: https://www.cveoy.top/t/topic/p1g3 著作权归作者所有。请勿转载和采集!