Removing non alphabetic character from string c++

2k Views Asked by At

This is driving me to the wall.

template<typename t>
void Tree<t>::readFromFile(string filename)
{
//
    str.erase( remove_if(str.begin(), str.end(), aZCheck), str.end());
//
}
template<typename t>
bool Tree<t>::aZCheck(char c)
{
    if (isalpha(c))
        return false;
    else return true;

}

Gives an error :cannot convert 'Tree<t>::aZCheck<std::basic_string<char> >' from type 'bool (Tree<std::basic_string<char> >::)(char)' to type 'bool (Tree<std::basic_string<char> >::*)(char)'|

Worked fine until I moved both methods into the class.

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

Doesnt work without using static cast and I am using cctype or ctype.h libraries, static cast is for c++ locale library which I am not using.

I can get it to work using static cast, but then I cant seem to make it negative !isalpha. As I need to delete non alphabetic characters and as it is , it will delete alphabetic ones. Forcing me into creating separate method, which I mentioned as my first issue. And it worked until I moved method into class.

Chances are I am missing something completely obvious, but I just cant figure it out...

3

There are 3 best solutions below

3
On BEST ANSWER

Declare the function as a static member function

static bool aZCheck(char c);

Take into account that the function could be defined simpler

template<typename t>
inline bool Tree<t>::aZCheck( char c )
{
    return isalpha( (unsigned char )c );

}
3
On

You should provide a free function (outside of class declaration) or a static member function for aZCheck().

 template<typename t>
 class Tree {
 public:
     static bool aZCheck(char c);
 };

and use

 str.erase( remove_if(str.begin(), str.end(), Tree<t>::aZCheck), str.end());

or better simply have a free function

 bool aZCheck(char c)  {
     return !isalpha(c));
 }

and use

 str.erase( remove_if(str.begin(), str.end(), aZCheck), str.end());
0
On

If your compiler supports C++11 and thus lambdas you could just:

  str.erase(std::remove_if(str.begin(), str.end(), [](char c) { return !isalpha(c); }), str.end());