Lines Iterator Versus Split Newline
str::lines recognizes and and strips them, yielding no trailing empty line, while split('\n') keeps and produces one.
Code
fn main() {
// 含 \r\n 的日志文本,结尾带换行
let log = "first\nsecond\r\nthird\n";
// lines():识别 \n 与 \r\n 并剥掉行尾,最后一个空行不产出
let via_lines: Vec<&str> = log.lines().collect();
println!("lines: {via_lines:?}");
// split('\n'):\r 留在片段里,结尾还多出一个空串
let via_split: Vec<&str> = log.split('\n').collect();
println!("split: {via_split:?}");
// 带行号日志:行尾不会再有看不见的 \r
for (no, line) in log.lines().enumerate() {
println!("{no}: {line:?}");
}
}How it works
Lines Iterator Versus Split Newline reduces to the function main.
The cycling part of this snippet is for (no, line) in log.lines().enumerate().
Points of care
- No dependency machinery at all — no registry and no lockfile entry.
Putting it to use
The callable shape is fn main()
The demo output is labeled (lines:, split:), so each line traces straight back to the statement that printed it.
Core lines
let via_split: Vec<&str> = log.split('\n').collect();
let via_lines: Vec<&str> = log.lines().collect();
Interactive Tools for This Topic
FAQ
- What does Lines Iterator Versus Split Newline print when run?
- Run it as a complete program — the output lines carry labels such as `lines:`, `split:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.