实现说明
Str Split Inclusive 保留终止符以函数 main为骨架。
本示例的循环部分是 for (index, part) in log.split_inclusive('\n').enumerate()。
使用要点
- 直接运行文件,输出会带上标签,比如
chunks:、lines:、inclusive count:——输出的每一行都能指回产生它的那次调用。
常见问题
运行「Str Split Inclusive 保留终止符」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 chunks:、lines:、inclusive count: 这类标签。
核心语句
let chunks: Vec<&str> = "a,b;c".split_inclusive(|c| c == ',' || c == ';').collect();
let tail: Vec<&str> = "one\ntwo".split_inclusive('\n').collect();
let without: Vec<&str> = log.lines().collect();
代码示例
fn main() {
let log = "start\nwork\nend";
// split_inclusive keeps the terminator on each yielded piece
for (index, part) in log.split_inclusive('\n').enumerate() {
println!("{index}: {part:?}");
}
// a predicate can mark any character as the boundary
let chunks: Vec<&str> = "a,b;c".split_inclusive(|c| c == ',' || c == ';').collect();
println!("chunks: {chunks:?}");
// lines removes the terminator, so the pieces differ
let without: Vec<&str> = log.lines().collect();
println!("lines: {without:?}");
println!("inclusive count: {}", log.split_inclusive('\n').count());
// the final piece has no terminator when the input lacks one
let tail: Vec<&str> = "one\ntwo".split_inclusive('\n').collect();
println!("tail: {tail:?}");
}