How to remove all the occurrences of a char in c++ string(如何删除c ++字符串中所有出现的字符)
问题描述
我正在使用以下内容:
replace (str1.begin(), str1.end(), 'a' , '')
但这会导致编译错误.
推荐答案
基本上,replace 将一个字符替换为另一个字符,而 '' 不是一个字符.你要找的是erase.
Basically, replace replaces a character with another and '' is not a character. What you're looking for is erase.
参见 这个问题,它回答了同样的问题.在你的情况下:
See this question which answers the same problem. In your case:
#include <algorithm>
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());
或者使用 boost 如果这是您的选择,例如:
Or use boost if that's an option for you, like:
#include <boost/algorithm/string.hpp>
boost::erase_all(str, "a");
所有这些都在 reference 网站.但是如果你不知道这些功能,你可以很容易地手工完成这种事情:
All of this is well-documented on reference websites. But if you didn't know of these functions, you could easily do this kind of things by hand:
std::string output;
output.reserve(str.size()); // optional, avoids buffer reallocations in the loop
for(size_t i = 0; i < str.size(); ++i)
if(str[i] != 'a') output += str[i];
这篇关于如何删除c ++字符串中所有出现的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何删除c ++字符串中所有出现的字符
基础教程推荐
- 提升 ASIO 流缓冲 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- c++ STL设置差异 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
