Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get indexes of all occurrences of a substring within a string

Tags:

rust

If I wanted to get the index of the first occurrence of, say, substring "foo" within a string "foo bar foo baz foo", I'd use:

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

...which would give me Some(0).

However, I need to find indexes of all occurrences of a substring within a string. In this scenario, I'd need something like:

[0, 8, 16]

How can I do this idiomatically in Rust?

like image 867
adder Avatar asked Feb 03 '26 14:02

adder


1 Answers

Use match_indices. Example from Rust docs:

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`
like image 160
Siborgium Avatar answered Feb 06 '26 13:02

Siborgium



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!