C++ Remove new line from multiline string

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

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

12条回答
  •  悲哀的现实
    2020-12-08 06:40

    Another way to do it in the for loop

    void rm_nl(string &s) {
        for (int p = s.find("\n"); p != (int) string::npos; p = s.find("\n"))
        s.erase(p,1);
    }
    

    Usage:

    string data = "\naaa\nbbb\nccc\nffffd\n";
    rm_nl(data); 
    cout << data; // data = aaabbbcccffffd
    

提交回复
热议问题