OneBite.Dev - Coding blog in a bite size

Find The Position Of The Last Occurrence Of A Substring In A String In Rust

Code snippet for how to Find The Position Of The Last Occurrence Of A Substring In A String In Rust with sample and detail explanation

Manipulating strings is a commonplace task in programming. Among these operations, one commonly used function is finding the position of the last occurrence of a particular substring within a string. In this article, we will learn how to do this in the Rust programming language.

Code snippet: Find The Position Of The Last Occurrence Of A Substring In A String In Rust

Here is a simple code snippet in Rust to find the position of the last occurrence of a substring in a string.

fn main() {
    let s = "The quick brown fox jumps over the lazy dog. The lazy dog sleeps.";
    let sub_string = "The lazy dog";

    if let Some(last_index) = s.rfind(&sub_string) {
        println!("The last occurrence of '{}' is at index {}", sub_string, last_index);
    } else {
        println!("'{}' not found.", sub_string);
    }   
}

Code Explanation for: Find The Position Of The Last Occurrence Of A Substring In A String In Rust

In this above code snippet, we’re manipulating the string defined by the variable s to find the last index of the substring sub_string which defaults to “The lazy dog”.

The main function first defines the string s and the substring sub_string. We then use the rfind method that’s implemented for Rust’s str data type, which performs a reverse find operation, starting from the end of the string and proceeding back to the beginning of the string. The function returns an Option type which can hold some value or no value. In this case, if the substring is found, it returns Some(index) and if it isn’t found, it returns None.

We handle this returned Option with the if let statement. If the rfind method returned an Some(index), the last_index variable is instantiated, and we print the index onto the console with the println! macro. If the rfind method returned None indicating that the sub-string was not found, we simply print ”’{}’ not found.”.

This snippet, therefore, prints out the index of the last occurrence of the requested substring in a string in Rust, or a helpful error message if the substring is not found.

rust