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?
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