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
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);
}
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.
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);
}