Remove spaces from std::string in C++

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

    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.

提交回复
热议问题