Longest Common Prefix Iterator
Derive the shared prefix of string slices by zipping character iterators and cutting at the first mismatch, no extra allocation.
Code
// 字节安全:匹配字符的 len_utf8 之和就是公共前缀的字节长度
fn longest_common_prefix<'a>(a: &'a str, b: &str) -> &'a str {
let common = a
.chars()
.zip(b.chars())
.take_while(|(x, y)| x == y)
.map(|(x, _)| x.len_utf8())
.sum::<usize>();
&a[..common]
}
fn main() {
let paths = ["deploy/web/prod", "deploy/web/stage", "deploy/api/prod"];
let mut prefix = paths[0];
for path in &paths[1..] {
prefix = longest_common_prefix(prefix, path);
}
println!("common prefix: {prefix:?}");
println!("{}", longest_common_prefix("listen", "list"));
println!("{:?}", longest_common_prefix("same", "same"));
println!("{:?}", longest_common_prefix("abc", "xyz"));
}How it works
Longest Common Prefix Iterator comes down to the functions longest_common_prefix and main.
A single loop drives the file — for path in &paths[1..].
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
Using it
Running the file prints labeled results such as common prefix: — each operation’s effect is visible in the output.
Running the file executes main, which drives longest_common_prefix in order.
Key statements
fn longest_common_prefix<'a>(a: &'a str, b: &str) -> &'a str {
let common = a
.chars()
.zip(b.chars())
.take_while(|(x, y)| x == y)
.map(|(x, _)| x.len_utf8())
.sum::<usize>();
&a[..common]
}
Interactive Tools for This Topic
FAQ
- What does Longest Common Prefix Iterator print when run?
- No setup needed: run the file and look for labeled lines like `common prefix:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.