14

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?

3 Answers 3

22

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`
Sign up to request clarification or add additional context in comments.

Comments

5

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]);

Comments

2

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")]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.