获取字符串中所有出现的子字符串的索引

ded*_*z69 1 rust

如果我想获得第一次出现的索引,比如说,字符串中的子"foo"字符串"foo bar foo baz foo",我会使用:

fn main() {
    let my_string = String::from("foo bar foo baz foo");
    println!("{:?}", my_string.find("foo"));
}
Run Code Online (Sandbox Code Playgroud)

...这会给我Some(0)

但是,我需要查找字符串中所有出现的子字符串的索引。在这种情况下,我需要类似的东西:

[0, 8, 16]
Run Code Online (Sandbox Code Playgroud)

我怎样才能在 Rust 中惯用地做到这一点?

小智 6

使用match_indices。Rust 文档中的示例:

let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);

let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
assert_eq!(v, [(1, "abc"), (4, "abc")]);

let v: Vec<_> = "ababa".match_indices("aba").collect();
assert_eq!(v, [(0, "aba")]); // only the first `aba`
Run Code Online (Sandbox Code Playgroud)