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?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
For trimming, use boost string algorithms:
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-
uses.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 1but as mentioned by others the erase remove idiom also seems fine.
You can use this solution for removing a char:
use it:
Can you use Boost String Algo? http://www.boost.org/doc/libs/1_35_0/doc/html/string_algo/usage.html#id1290573
If you want to do this with an easy macro, here's one:
This assumes you have done
#include <string>
of course.Call it like so: