Remove single trailing newline from String without cloning

前端 未结 3 883
猫巷女王i
猫巷女王i 2020-12-11 00:13

I have written a function to prompt for input and return the result. In this version the returned string includes a trailing newline from the user. I would like to return th

3条回答
  •  我在风中等你
    2020-12-11 01:06

    A cross-platform way of stripping a single trailing newline without reallocating the string is this:

    fn trim_newline(s: &mut String) {
        if s.ends_with('\n') {
            s.pop();
            if s.ends_with('\r') {
                s.pop();
            }
        }
    }
    

    This will strip either "\n" or "\r\n" from the end of the string, but no additional whitespace.

提交回复
热议问题