从字符串中删除字符

时间:2010-12-27 10:05:34

标签: c++ string

我有一个字符串。我想删除字符串的最后一个字符(如果它是一个空格)。 我尝试了以下代码,

str.erase(remove_if(str.begin(), str.end(), isspace), str.end());

但我的g ++编译器给出了一个错误说:

error: no matching function for call to ‘remove_if(__gnu_cxx::__normal_iterator<char*,
std::basic_string<char, std::char_traits<char>, std::allocator<char> > >,
__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > >, <unresolved overloaded function type>)’

请帮忙。

4 个答案:

答案 0 :(得分:7)

第一个问题是isspace在C ++标准库中有多个重载。初始修复是为函数提供显式类型,以便编译器知道采用以下地址的函数:

#include <string>
#include <algorithm>
#include <cctype>

int main()
{
   std::string str = "lol hi innit";
   str.erase(std::remove_if(str.begin(), str.end(), (int(*)(int))isspace), str.end());
   std::cout << str; // will output: "lolhiinnit"
}

这很难看,但是,嘿,这是C ++。

其次,您的代码将删除字符串中的所有空格,这不是您想要的。考虑一下字符串最后一个字符的简单if语句:

#include <string>
#include <cassert>

int main()
{
   std::string str = "lol hi innit ";
   assert(!str.empty());

   if (*str.rbegin() == ' ')
      str.resize(str.length()-1);

   std::cout << "[" << str << "]"; // will output: "[lol hi innit]"
}

希望这有帮助。

答案 1 :(得分:6)

我认为它无法弄清楚isspace是什么(根据“未解析的重载函数类型”作为错误消息中remove_if的第三个参数)。试试::isspace,并加入ctype.h

答案 2 :(得分:0)

我和你有完全相同的问题,所以我摆脱了isspace。我刚刚接受了这个:

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

使用Visual Studio 2012,Visual C ++ 2012对我有用。看看它是否适合您。

答案 3 :(得分:-2)

您错过了std::

remove_if
相关问题