Remove single trailing newline from String without cloning

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

提交回复
热议问题