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?
If you want to do this with an easy macro, here's one:
#define REMOVE_SPACES(x) x.erase(std::remove(x.begin(), x.end(), ' '), x.end())
This assumes you have done #include <string>
of course.
Call it like so:
std::string sName = " Example Name ";
REMOVE_SPACES(sName);
printf("%s",sName.c_str()); // requires #include <stdio.h>
From gamedev
string.erase(std::remove_if(string.begin(), string.end(), std::isspace), string.end());
Removes all whitespace characters such as tabs and line breaks (C++11):
string str = " \n AB cd \t efg\v\n";
str = regex_replace(str,regex("\\s"),"");
In C++20 you can use free function std::erase
std::string str = " Hello World !";
std::erase(str, ' ');
Full example:
#include<string>
#include<iostream>
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
I used the below work around for long - not sure about its complexity.
s.erase(std::unique(s.begin(),s.end(),[](char s,char f){return (f==' '||s==' ');}),s.end());
when you wanna remove character ' '
and some for example -
use
s.erase(std::unique(s.begin(),s.end(),[](char s,char f){return ((f==' '||s==' ')||(f=='-'||s=='-'));}),s.end());
likewise just increase the ||
if number of characters you wanna remove is not 1
but as mentioned by others the erase remove idiom also seems fine.