fn basename<'a>(path: &'a str, sep: char) -> Cow<'a, str> {
let pieces = path.split(sep);
match pieces.last() {
Some(p) => p.into(),
None => path.into(),
}
}
Usage:
println!("'{}'", basename("foo", '/')); // outputs 'foo'
println!("'{}'", basename("bob/", '/')); // outputs ''
println!("'{}'", basename("/usr/local/bin/rustc", '/')); // outputs 'rustc'
I think the split()
into a match
on last()
is kind of elegant.
I know there is some work needed to handle both str
and String
, I am not sold on the use of Cow
and needing to define a lifetime for the string.
I am not sold on Cow
because later on I need to extract from it.
let prog = basename(&args[0], '/').into_owned();
It feels like I am working too hard.
lastIndexOf
to find the last occurrence of a substring within a string. \$\endgroup\$last()
is doing @SimonAndréForsberg. In Rust thesplit()
makes an iterator. Converting it to an array or the like would be a bit of overkill. \$\endgroup\$