C++ Remove new line from multiline string

前端 未结 12 2307
暗喜
暗喜 2020-12-08 06:14

Whats the most efficient way of removing a \'newline\' from a std::string?

相关标签:
12条回答
  • 2020-12-08 06:45

    Here is one for DOS or Unix new line:

        void chomp( string &s)
        {
                int pos;
                if((pos=s.find('\n')) != string::npos)
                        s.erase(pos);
        }
    
    0 讨论(0)
  • 2020-12-08 06:45

    Use std::algorithms. This question has some suitably reusable suggestions Remove spaces from std::string in C++

    0 讨论(0)
  • 2020-12-08 06:49

    The code removes all newlines from the string str.

    O(N) implementation best served without comments on SO and with comments in production.

    unsigned shift=0;
    for (unsigned i=0; i<length(str); ++i){
        if (str[i] == '\n') {
            ++shift;
        }else{
            str[i-shift] = str[i];
        }
    }
    str.resize(str.length() - shift);
    
    0 讨论(0)
  • 2020-12-08 06:50
    #include <algorithm>
    #include <string>
    
    std::string str;
    
    str.erase(std::remove(str.begin(), str.end(), '\n'), str.end());
    

    The behavior of std::remove may not quite be what you'd expect. See an explanation of it here.

    0 讨论(0)
  • 2020-12-08 06:54

    About answer 3 removing only the last \n off string code :

    if (!s.empty() && s[s.length()-1] == '\n') {
        s.erase(s.length()-1);
    }
    

    Will the if condition not fail if the string is really empty ?

    Is it not better to do :

    if (!s.empty())
    {
        if (s[s.length()-1] == '\n')
            s.erase(s.length()-1);
    }
    
    0 讨论(0)
  • 2020-12-08 06:55
    s.erase(std::remove(s.begin(), s.end(), '\n'), s.end());
    
    0 讨论(0)
提交回复
热议问题