Is there a find function in Rust's standard library which searches for a substring starting at a given index in the string? Just like indexOf in JavaScript.
Is there a find function in Rust's standard library which searches for a substring starting at a given index in the string? Just like indexOf in JavaScript.
You would use str::find on a substr and then add the offset back:
let s = "foobarfoo";
let index: Option<usize> = s[4..].find("foo").map(|i| i + 4);
println!("{:?}", index);
Some(6)
I can think of two ways:
Use the .get() method to safely get a slice of an ASCII string and then apply .find to that.
let s = "foobarfoo";
let res = s.get(4..).and_then(|s| s.find("foo").map(|i| i + 4));
Use match_indices to iterate over matches and their indices and then find_map the one that matches the first condition.
let s = "foobarfoo";
let res = s.match_indices("foo").find_map(|(i, _)| (i >= 4).then(|| i));
Some(6).None.