Remove single trailing newline from String without cloning

前端 未结 3 877
猫巷女王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:04

    You can use String::pop or String::truncate:

    fn main() {
        let mut s = "hello\n".to_string();
        s.pop();
        assert_eq!("hello", &s);
    
        let mut s = "hello\n".to_string();
        let len = s.len();
        s.truncate(len - 1);
        assert_eq!("hello", &s);
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-11 01:06

    A more generic solution than the accepted one, that works with any kind of line ending:

    fn main() {
        let mut s = "hello\r\n".to_string();
        let len_withoutcrlf = s.trim_right().len();
        s.truncate(len_withoutcrlf);
        assert_eq!("hello", &s);
    }
    
    0 讨论(0)
提交回复
热议问题