Remove spaces from std::string in C++

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

    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>
    
    0 讨论(0)
  • 2020-11-22 17:40

    From gamedev

    string.erase(std::remove_if(string.begin(), string.end(), std::isspace), string.end());
    
    0 讨论(0)
  • 2020-11-22 17:40

    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"),"");
    
    0 讨论(0)
  • 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<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

    0 讨论(0)
  • 2020-11-22 17:46

    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.

    0 讨论(0)
提交回复
热议问题