开发者

Removing a character from a string

i have a string. I want to delete the last character of the string if it is a space. i tried the following code,

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

but my g++ compiler gives me an error saying:

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>)’

please help.


The first problem is that isspace has multiple overloads in the C++ Standard Library. The initial fix is to provide an explicit type for the function so that the compiler knows which function to take the address of:

#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"
}

It's a big ugly but, hey, this is C++.

Second, your code will remove all spaces in the string, which is not what you seem to want. Consider a simple if statement on the last character of the string:

#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]"
}

Hope this helps.


I think it can't figure out what isspace is (according to the "unresolved overloaded function type" as a third parameter to remove_if in the error message). Try ::isspace, and include ctype.h


I had the exact same problem as you, so I got rid of isspace. I just went with this:

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

That worked for me with Visual C++ 2012, using Visual Studio 2012. See if it works for you.


You are missing an std:: for remove_if

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜