Find sub strings

Hello community,

I want to find sub strings and return the indexes from long string. If the sub strings occur multiple times in the long string, find out all of the sub strings. Suggestions are welcome.

Thanks

fn main() {
    let long_string = "aaa bbb ccc bbb bbb";
    let sub_string = "bbb";
    let len = long_string.len();
    let mut index: usize = 0;

    while index != len {
        let i = long_string[index..].find(sub_string);
        if let Some(i) = i {
            index += i;
            println!("{:?}", index);
            index += 1;
        } else {
            break;
        }
    }
}

Please consult the standard library documentation before asking to see if there's anything relevant to your problem. This task is completely solved by str::match_indices().

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.