Remove spaces from std::string in C++

后端 未结 17 1613
说谎
说谎 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:42

    In C++20 you can use free function std::erase

    std::string str = " Hello World  !";
    std::erase(str, ' ');
    

    Full example:

    #include
    #include
    
    int main() {
        std::string str = " Hello World  !";
        std::erase(str, ' ');
        std::cout << "|" << str <<"|";
    }
    

    I print | so that it is obvious that space at the begining is also removed.

    note: this removes only the space, not every other possible character that may be considered whitespace, see https://en.cppreference.com/w/cpp/string/byte/isspace

提交回复
热议问题