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.
-
We start by defining the main function:
fn main()
. This is the entry point of our Rust program. -
Inside the main function, we define two string variables,
haystack
andneedle
. Thehaystack
contains the larger string that we want to search within, andneedle
contains the smaller string that we want to find.let haystack = "Hello, world!"; let needle = "world";
-
Next, we use the
.find()
method onhaystack
. This method receivesneedle
as the argument and returns anOption<usize>
. This means it either returnsSome(index)
with the index being the position of the first occurrence ofneedle
inhaystack
, orNone
ifneedle
wasn’t found at all.let position = haystack.find(needle);
-
Finally, we handle both possible outcomes of the
.find()
method with amatch
expression. Ifposition
isSome(index)
, we print the index whereneedle
was found. Ifposition
isNone
, we print a message indicating thatneedle
wasn’t found inhaystack
.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.