C++ Remove punctuation from String

后端 未结 12 2466
天涯浪人
天涯浪人 2020-11-29 07:02

I got a string and I want to remove all the punctuations from it. How do I do that? I did some research and found that people use the ispunct() function (I tried that), but

12条回答
  •  醉酒成梦
    2020-11-29 07:28

    I tried to apply @Steve314's answer but couldn't get it to work until I came across this note here on cppreference.com:

    Notes

    Like all other functions from , the behavior of std::ispunct is undefined if the argument's value is neither representable as unsigned char nor equal to EOF. To use these functions safely with plain chars (or signed chars), the argument should first be converted to unsigned char.

    By studying the example it provides, I am able to make it work like this:

    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        std::string text = "this. is my string. it's here.";
        std::string result;
        text.erase(std::remove_if(text.begin(),
                                  text.end(),
                                  [](unsigned char c) { return std::ispunct(c); }),
                   text.end());
        std::cout << text << std::endl;
    }
    

提交回复
热议问题