Sub topic 4
Trimming the Trailing Newline
What this chapter assumes
You should be comfortable with String versus &str, mutable references, and match on a Result. You should also know how to run a program with cargo run. The previous chapters showed how to call read_line and handle its io::Result. This chapter covers what is in the buffer afterward and how to clean it up.
Why the newline is there
read_line reads from the input stream until it has consumed a newline character, then appends everything it read, newline included, to your String. The newline is the Enter key you pressed, and Rust does not remove it for you. Look at the buffer with the Debug format ({:?}), which shows escape sequences:
use std::io;
fn main() -> io::Result<()> {
let mut input = String::new();
io::stdin().read_line(&mut input)?;
println!("raw: {:?}", input);
println!("trimmed: {:?}", input.trim());
println!("bytes before: {}, after: {}", input.len(), input.trim().len());
Ok(())
}If you type hello and press Enter, the output is:
raw: "hello\n"
trimmed: "hello"
bytes before: 6, after: 5Use {:?} whenever you debug input handling. Plain {} hides the newline, so a bug that comes from it looks like correct output.
What goes wrong without trimming
The newline is part of the string, so any later use of that string sees it. Parsing is the most common casualty:
fn main() {
let raw = "42\n";
println!("{:?}", raw.parse::<u32>());
println!("{:?}", raw.trim().parse::<u32>());
}Err(ParseIntError { kind: InvalidDigit })
Ok(42)parse accepts only the characters that make up a number. It does not skip surrounding whitespace, so "42\n" is rejected.
Comparisons fail in the same way. input == "yes" is false when input holds "yes\n", and the program takes the wrong branch without any error. Trim before you parse or compare.
The trimming methods
str has several trimming methods. They all return a &str that borrows from the original text.
| Method | Removes | `" hi \r\n"` becomes |
|---|---|---|
| `trim()` | Whitespace at both ends | `"hi"` |
| `trim_start()` | Whitespace at the start | `"hi \r\n"` |
| `trim_end()` | Whitespace at the end | `" hi"` |
| `trim_end_matches(pattern)` | Repeated matches of a pattern at the end | depends on the pattern |
| `strip_suffix(pattern)` | One occurrence of a suffix, returned as an `Option` | depends on the suffix |
"Whitespace" here means any character with the Unicode White_Space property. That covers spaces, tabs, \n, \r, and also characters such as the non-breaking space. A short program shows the difference:
fn main() {
let raw = " hello world \r\n";
println!("{:?}", raw.trim());
println!("{:?}", raw.trim_start());
println!("{:?}", raw.trim_end());
println!(
"{:?}",
raw.trim_end_matches(|c: char| c == '\r' || c == '\n')
);
}"hello world"
"hello world \r\n"
" hello world"
" hello world "The last line keeps the spaces and removes only the line ending.
Trimming costs nothing and borrows the buffer
trim does not copy or allocate. It scans inward from both ends and returns a slice of the original bytes. The result has the same lifetime as the String it came from.
That has two consequences. First, you cannot change the buffer while a trimmed slice of it is still in use, because the slice would point at memory that may move. Second, if you need the value to outlive the buffer, you must make an owned copy with to_string() or to_owned().
This matters when you reuse one buffer for several reads. read_line appends to the string, so you must call clear before each new read:
use std::io;
fn main() -> io::Result<()> {
let mut buffer = String::new();
let mut names: Vec<String> = Vec::new();
for _ in 0..3 {
buffer.clear();
if io::stdin().read_line(&mut buffer)? == 0 {
break;
}
names.push(buffer.trim().to_string());
}
println!("{names:?}");
Ok(())
}The to_string() call is what lets buffer.clear() run safely on the next pass. If you pushed the &str from trim() into a Vec<&str> instead, the compiler would reject the program with a borrow error, because clear needs a mutable borrow while the slices are still alive.
A related pattern is shadowing: let input = input.trim();. It compiles and reads well, but the original String is still alive and still borrowed by the new name. It is fine inside a single function when you do not reuse the buffer.
Line endings differ by platform
On Unix-like systems, pressing Enter produces \n. A terminal on Windows typically produces \r\n. Piped files can use either form, regardless of the operating system. read_line splits only on \n, so a Windows-style line arrives as "text\r\n". The \r is a real character in your string.
trim and trim_end remove both characters, so they handle either style. If you trim with trim_end_matches('\n') alone, a trailing \r survives, and parsing fails with the same confusing InvalidDigit error.
Removing only the line ending
Plain trim also removes spaces and tabs that the user typed deliberately. Sometimes you want to keep those, for example when a program echoes text back exactly, handles a password where leading or trailing spaces are legal, or processes fixed-width records. In those cases, remove just the line ending.
strip_suffix returns Some(rest) if the suffix is present and None if it is not. Combining two calls handles both \n and \r\n:
fn strip_line_ending(s: &str) -> &str {
s.strip_suffix('\n')
.map(|rest| rest.strip_suffix('\r').unwrap_or(rest))
.unwrap_or(s)
}
fn main() {
assert_eq!(strip_line_ending("abc\n"), "abc");
assert_eq!(strip_line_ending("abc\r\n"), "abc");
assert_eq!(strip_line_ending("abc"), "abc");
assert_eq!(strip_line_ending("abc \n"), "abc ");
assert_eq!(strip_line_ending("abc\r"), "abc\r");
println!("all checks passed");
}The function removes at most one \n, and a \r only when it comes directly before that \n. A lone \r with no \n is left alone, as the last assertion shows. trim_end_matches would instead strip every trailing match, so "abc\n\n" would lose both newlines.
The flow from keyboard to typed value looks like this:
Edge cases to know
- Empty line. If the user presses Enter on its own, the buffer holds
"\n"andtrim()returns"". The read succeeded, and the line is empty. Parsing""as a number fails, and your code should treat that as bad input, not as a crash. - End of input. At end of input,
read_linereturnsOk(0)and leaves the buffer empty. Aftertrim, that looks the same as an empty line. Check the byte count thatread_linereturns before you trim if you need to tell the two cases apart. The chapter on end of input covers this. - Last line without a newline. When input comes from a file or pipe, the final line may have no trailing
\n.trimhandles this without special code, which is one reason to prefer it over removing a fixed number of bytes. - Never slice off the last byte. Code like
&input[..input.len() - 1]removes the wrong thing when the line ends in\r\nor has no newline at all. It can also panic if the last character is not one byte wide. Usetrim,trim_end, orstrip_suffix. - Interior whitespace stays.
trimtouches only the ends." hello world \n"becomes"hello world". To split on interior whitespace, usesplit_whitespace, which a later chapter covers.
Choosing a method
- For numbers, menu choices, and yes/no answers, use
trim(). Extra spaces around such values are never meaningful. - For text where leading or trailing spaces carry meaning, use
strip_suffix(or a helper likestrip_line_ending) so only the line ending goes. - For output that must match the input byte for byte, do not trim at all. Write the raw string back.
Summary of the working model
read_line gives you the raw line, including its terminator. trim gives you a borrowed view of that line without surrounding whitespace, at no allocation cost. Parse and compare the trimmed view. Copy it into an owned String only when the value must live longer than the buffer. When whitespace is meaningful, strip just the line ending with strip_suffix.
Exercise
A program reads a line with read_line and runs on a Windows machine with input piped from a file. The code calls input.trim_end_matches('\n').parse::<i32>() and fails with InvalidDigit for the line 7. Why, and what are two ways to fix it?
Show answer
The file uses \r\n line endings, so the buffer holds "7\r\n". trim_end_matches('\n') removes only the \n, which leaves "7\r", and parse rejects the \r. One fix is to call trim() (or trim_end()), which removes both characters. The other is to strip the line ending explicitly with strip_suffix('\n') followed by strip_suffix('\r'), as in strip_line_ending, or to use trim_end_matches(|c: char| c == '\r' || c == '\n').
Exercise
This loop is meant to collect three trimmed lines. What is wrong with it, and how do you fix it? let mut buffer = String::new(); let mut lines: Vec<&str> = Vec::new(); for in 0..3 { buffer.clear(); io::stdin().readline(&mut buffer)?; lines.push(buffer.trim()); }
Show answer
buffer.trim() borrows from buffer, and the loop then calls buffer.clear(), which needs a mutable borrow while earlier slices are still stored in lines. The compiler rejects this with a borrow error. Change lines to Vec<String> and push buffer.trim().to_string(), so each stored line is an owned copy that does not depend on the buffer.