Split Terminator Skips Empty Tail
Choose split_terminator over split when a trailing separator should end the record, not start an empty one — the classic newline-difference.
Code
fn main() {
let frames = "ping\npong\n";
// split:结尾的分隔符会多出一个空片段
let pieces: Vec<&str> = frames.split('\n').collect();
println!("split: {pieces:?}");
// split_terminator:结尾分隔符只表示“记录结束”,不产生空尾
let records: Vec<&str> = frames.split_terminator('\n').collect();
println!("terminator: {records:?}");
// 中间的连续分隔符两侧行为一致:仍产生空片段
let ragged = "a,,b";
println!("split: {:?}", ragged.split(',').collect::<Vec<_>>());
println!("terminator: {:?}", ragged.split_terminator(',').collect::<Vec<_>>());
}How the snippet works
Split Terminator Skips Empty Tail reduces to the function main.
Applying it
Running the file prints labeled results such as split:, terminator: — each operation’s effect is visible in the output.
Statements that matter
let records: Vec<&str> = frames.split_terminator('\n').collect();
let pieces: Vec<&str> = frames.split('\n').collect();
Interactive Tools for This Topic
FAQ
- What does Split Terminator Skips Empty Tail print when run?
- No setup needed: run the file and look for labeled lines like `split:`, `terminator:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.