How to strip all non alphanumeric characters from a string in c++?

后端 未结 11 1329
野的像风
野的像风 2020-11-30 02:07

I am writing a piece of software, and It require me to handle data I get from a webpage with libcurl. When I get the data, for some reason it has extra line breaks in it. I

相关标签:
11条回答
  • 2020-11-30 02:35

    You can use the remove-erase algorithm this way -

    // Removes all punctuation       
    s.erase( std::remove_if(s.begin(), s.end(), &ispunct), s.end());
    
    0 讨论(0)
  • 2020-11-30 02:36

    The following works for me.

    str.erase(std::remove_if(str.begin(), str.end(), &ispunct), str.end());
    str.erase(std::remove_if(str.begin(), str.end(), &isspace), str.end());
    
    0 讨论(0)
  • 2020-11-30 02:41

    Just extending James McNellis's code a little bit more. His function is deleting alnum characters instead of non-alnum ones.

    To delete non-alnum characters from a string. (alnum = alphabetical or numeric)

    • Declare a function (isalnum returns 0 if passed char is not alnum)

      bool isNotAlnum(char c) {
          return isalnum(c) == 0;
      }
      
    • And then write this

      s.erase(remove_if(s.begin(), s.end(), isNotAlnum), s.end());
      

    then your string is only with alnum characters.

    0 讨论(0)
  • 2020-11-30 02:41

    The mentioned solution

    s.erase( std::remove_if(s.begin(), s.end(), &std::ispunct), s.end());
    

    is very nice, but unfortunately doesn't work with characters like 'Ñ' in Visual Studio (debug mode), because of this line:

    _ASSERTE((unsigned)(c + 1) <= 256)
    

    in isctype.c

    So, I would recommend something like this:

    inline int my_ispunct( int ch )
    {
        return std::ispunct(unsigned char(ch));
    }
    ...
    s.erase( std::remove_if(s.begin(), s.end(), &my_ispunct), s.end());
    
    0 讨论(0)
  • 2020-11-30 02:46
    void remove_spaces(string data)
    { int i=0,j=0;
        while(i<data.length())
        {
            if (isalpha(data[i]))
            {
            data[i]=data[i];
            i++;
            }
            else
                {
                data.erase(i,1);}
        }
        cout<<data;
    }
    
    0 讨论(0)
提交回复
热议问题