Find The Index Of A Substring Within A String In Rust
Code snippet for how to Find The Index Of A Substring Within A String In Rust with sample and detail explanation
In the world of programming, finding the index of a substring within a string is a common requirement that programmers face often. This article will provide you with an easy understanding of finding the string index in Rust.
Code snippet: Finding the Index of a Substring within a String in Rust
let main_string = "Hello, Rust programmers!";
let sub_string = "Rust";
match main_string.find(sub_string) {
Some(index_of_substring) => println!("Found {} at index {}", sub_string, index_of_substring),
None => println!("{} not found in '{}'", sub_string, main_string),
}
Code Explanation: Finding the Index of a Substring within a String in Rust
The above example uses Rust’s in-built find()
function to locate the index of a substring within a string. The code is self-explanatory, yet it is always beneficial to understand it at a deeper level. Let’s break it down:
-
let main_string = "Hello, Rust programmers!";
: This line sets up a string called “main_string”. This is the string that will be searched. -
let sub_string = "Rust";
: This line sets up the ‘sub_string’. This is the string that we want to find within the ‘main_string’. -
match main_string.find(sub_string) {
: Thefind()
function is called on ‘main_string’ and ‘sub_string’ is passed as a parameter. Thefind()
function returns an Option that contains the start index of the ‘sub_string’. If the ‘sub_string’ is not found, it returns ‘None’. Using ‘match’ allows us to handle both of these outcomes. -
Some(index_of_substring) => println!("Found {} at index {}", sub_string, index_of_substring),
: If the ‘sub_string’ is found within the ‘main_string’, the returned value will match ‘Some(index_of_substring)‘. Then it will print a message indicating the ‘sub_string’ and the index where it was found. -
None => println!("{} not found in '{}'", sub_string, main_string),
: If the ‘sub_string’ is not found within the ‘main_string’, it will match ‘None’ and print a message saying that the ‘sub_string’ was not found in the ‘main_string’.