如何删除c ++字符串中所有字符的出现 [英] How to remove all the occurrences of a char in c++ string

查看:285
本文介绍了如何删除c ++字符串中所有字符的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下:

replace (str1.begin(), str1.end(), 'a' , '')

但这是编译错误。

推荐答案

基本上,替换为另一个字符和 >不是字符。您要查找的是 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:

str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());

或使用 boost you,like:

Or use boost if that's an option for you, like:

#include <boost/algorithm/string.hpp>
boost::erase_all(str, "a");

所有这些都在参考 网站。但是如果你不知道这些函数,你可以很容易地手工做这样的事情:

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 ++字符串中所有字符的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆