C++ Remove punctuation from String

后端 未结 12 2431
天涯浪人
天涯浪人 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条回答
  •  -上瘾入骨i
    2020-11-29 07:33

    #include 
    #include 
    #include 
    
    int main() {
    
        std::string text = "this. is my string. it's here.";
    
        for (int i = 0, len = text.size(); i < len; i++)
        {
            if (ispunct(text[i]))
            {
                text.erase(i--, 1);
                len = text.size();
            }
        }
    
        std::cout << text;
        return 0;
    }
    

    Output

    this is my string its here
    

    When you delete a character, the size of the string changes. It has to be updated whenever deletion occurs. And, you deleted the current character, so the next character becomes the current character. If you don't decrement the loop counter, the character next to the punctuation character will not be checked.

提交回复
热议问题