OneBite.Dev - Coding blog in a bite size

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

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

Finding the position of the first occurrence of a substring in a string is a common task in programming. In this article, we will implement this task in Rust, a modern, performance-driven programming language.

Code snippet for Finding the Position of the First Occurrence of a Substring in a String in Rust

fn main() {
    let haystack = "Hello, world!";
    let needle = "world";
    let position = haystack.find(needle);

    match position {
        Some(index) => println!("'{}' found at position {}", needle, index),
        None => println!("'{}' not found in '{}'", needle, haystack),
    }
}

Code Explanation for Finding the Position of the First Occurrence of a Substring in a String in Rust

Let’s go through this Rust code snippet step by step for better understanding.

  1. We start by defining the main function: fn main(). This is the entry point of our Rust program.

  2. Inside the main function, we define two string variables, haystack and needle. The haystack contains the larger string that we want to search within, and needle contains the smaller string that we want to find.

    let haystack = "Hello, world!";
    let needle = "world";
  3. Next, we use the .find() method on haystack. This method receives needle as the argument and returns an Option<usize>. This means it either returns Some(index) with the index being the position of the first occurrence of needle in haystack, or None if needle wasn’t found at all.

    let position = haystack.find(needle);
  4. Finally, we handle both possible outcomes of the .find() method with a match expression. If position is Some(index), we print the index where needle was found. If position is None, we print a message indicating that needle wasn’t found in haystack.

    match position {
        Some(index) => println!("'{}' found at position {}", needle, index),
        None => println!("'{}' not found in '{}'", needle, haystack),
    }

That’s it! Using this simple Rust code, we can easily find the position of the first occurrence of a substring in a string.

rust