Remove spaces from std::string in C++

后端 未结 17 1614
说谎
说谎 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 of course.

    Call it like so:

    std::string sName = " Example Name ";
    REMOVE_SPACES(sName);
    printf("%s",sName.c_str()); // requires #include 
    

提交回复
热议问题