Removing a character from a string

c++, string

Solution

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.

Problem

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.

Original source