Reputation: 1715
I have a string: "abcd" and I want to:
Iterate its prefixes from shortest to longest:
"", "a", "ab", "abc", "abcd"
Iterate its prefixes from longest to shortest:
"abcd", "abc", "ab", "a", ""
Iterate its suffixes from shortest to longest:
"", "d", "cd", "bcd", "abcd"
Iterate its suffixes from longest to shortest:
"abcd", "bcd", "cd", "d", ""
Upvotes: 2
Views: 1262
Reputation: 1715
#[cfg(test)]
mod tests {
#[test]
#[should_panic(expected = "byte index 2 is not a char boundary; it is inside '\\u{306}' (bytes 1..3) of `y̆`")]
fn bad_index() {
let y = "y̆";
&y[2..];
}
}
To work at the code point level rust has:
Further reading: https://doc.rust-lang.org/book/ch08-02-strings.html
Warning: this code works at the code point level and is grapheme cluster oblivious.
From shortest to longest:
use core::iter;
pub fn prefixes(s: &str) -> impl Iterator<Item = &str> + DoubleEndedIterator {
s.char_indices()
.map(move |(pos, _)| &s[..pos])
.chain(iter::once(s))
}
pub fn suffixes(s: &str) -> impl Iterator<Item = &str> + DoubleEndedIterator {
s.char_indices()
.map(move |(pos, _)| &s[pos..])
.chain(iter::once(""))
.rev()
}
In reverse:
prefixes(s).rev()
suffixes(s).rev()
See also: How to iterate prefixes or suffixes of vec or slice in rust?
Upvotes: 5