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?
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.