C++ Remove punctuation from String

后端 未结 12 2468
天涯浪人
天涯浪人 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:36

    Another way you could do this would be as follows:

    #include  //needed for ispunct()
    string onlyLetters(string str){
        string retStr = "";
    
        for(int i = 0; i < str.length(); i++){
            if(!ispunct(str[i])){
                retStr += str[i];
            }
        }
        return retStr;
    

    This ends up creating a new string instead of actually erasing the characters from the old string, but it is a little easier to wrap your head around than using some of the more complex built in functions.

提交回复
热议问题