Remove single trailing newline from String without cloning

前端 未结 3 885
猫巷女王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 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);
    }
    

提交回复
热议问题