Remove spaces from std::string in C++

后端 未结 17 1671
说谎
说谎 2020-11-22 16:47

What is the preferred way to remove spaces from a string in C++? I could loop through all the characters and build a new string, but is there a better way?

17条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 17:28

    Hi, you can do something like that. This function deletes all spaces.

    string delSpaces(string &str) 
    {
       str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
       return str;
    }
    

    I made another function, that deletes all unnecessary spaces.

    string delUnnecessary(string &str)
    {
        int size = str.length();
        for(int j = 0; j<=size; j++)
        {
            for(int i = 0; i <=j; i++)
            {
                if(str[i] == ' ' && str[i+1] == ' ')
                {
                    str.erase(str.begin() + i);
                }
                else if(str[0]== ' ')
                {
                    str.erase(str.begin());
                }
                else if(str[i] == '\0' && str[i-1]== ' ')
                {
                    str.erase(str.end() - 1);
                }
            }
        }
        return str;
    }
    

提交回复
热议问题