Remove spaces from std::string in C++

后端 未结 17 1397
说谎
说谎 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:28
    string removespace(string str)
    {    
        int m = str.length();
        int i=0;
        while(i<m)
        {
            while(str[i] == 32)
            str.erase(i,1);
            i++;
        }    
    }
    
    0 讨论(0)
  • 2020-11-22 17:29

    You can use this solution for removing a char:

    #include <algorithm>
    #include <string>
    using namespace std;
    
    str.erase(remove(str.begin(), str.end(), char_to_remove), str.end());
    
    0 讨论(0)
  • 2020-11-22 17:29

    For trimming, use boost string algorithms:

    #include <boost/algorithm/string.hpp>
    
    using namespace std;
    using namespace boost;
    
    // ...
    
    string str1(" hello world! ");
    trim(str1);      // str1 == "hello world!"
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 17:35
       #include <algorithm>
       using namespace std;
    
       int main() {
           .
           .
           s.erase( remove( s.begin(), s.end(), ' ' ), s.end() );
           .
           .
       }
    

    Source:

    Reference taken from this forum.

    0 讨论(0)
  • 2020-11-22 17:37

    The best thing to do is to use the algorithm remove_if and isspace:

    remove_if(str.begin(), str.end(), 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:

    str.erase(remove_if(str.begin(), str.end(), isspace), str.end());
    

    We should also note that remove_if will make at most one copy of the data. Here is a sample implementation:

    template<typename T, typename P>
    T remove_if(T beg, T end, P pred)
    {
        T dest = beg;
        for (T itr = beg;itr != end; ++itr)
            if (!pred(*itr))
                *(dest++) = *itr;
        return dest;
    }
    
    0 讨论(0)
提交回复
热议问题