C++ Remove new line from multiline string

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

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

12条回答
  •  一向
    一向 (楼主)
    2020-12-08 06:44

    If the newline is expected to be at the end of the string, then:

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

    If the string can contain many newlines anywhere in the string:

    std::string::size_type i = 0;
    while (i < s.length()) {
        i = s.find('\n', i);
        if (i == std::string:npos) {
            break;
        }
        s.erase(i);
    }
    

提交回复
热议问题