adder
adder

Reputation: 3698

Get indexes of all occurrences of a substring within a string

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?

Upvotes: 13

Views: 9966

Answers (3)

Ashford Nichols
Ashford Nichols

Reputation: 176

I think the most complete answer, based on the OP's requirement, would be:

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

Upvotes: 5

Alexander Fadeev
Alexander Fadeev

Reputation: 2626

There is a match_indices: https://doc.rust-lang.org/std/string/struct.String.html#method.match_indices

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

Upvotes: 2

Siborgium
Siborgium

Reputation: 426

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`

Upvotes: 21

Related Questions