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
I'm afraid it's the best solution that I can think of. But you can use reserve() to pre-allocate the minimum required memory in advance to speed up things a bit. You'll end up with a new string that will probably be shorter but that takes up the same amount of memory, but you'll avoid reallocations.
EDIT: Depending on your situation, this may incur less overhead than jumbling characters around.
You should try different approaches and see what is best for you: you might not have any performance issues at all.
The best thing to do is to use the algorithm
remove_if
and isspace:Now the algorithm itself can't change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase to actually modify the length of the container:
We should also note that remove_if will make at most one copy of the data. Here is a sample implementation:
From gamedev
Hi, you can do something like that. This function deletes all spaces.
I made another function, that deletes all unnecessary spaces.