What is the string.find() method in Rust?
Overview
In Rust, the find() method is used to find the first match of a specified character or another string. It returns the byte index of the first character of the specified character or string in the case of a successful match, and None in case of an unsuccessful match.
Syntax
string.find(match)
Syntax for find() method in Rust
Parameters
This method takes two parameters:
match: This is the string or character searched for in a string,string: This is the string in which the method searches formatch.
Return value
This method returns the byte index of the first character of the match. For example: Some(2), Some(14). For no match, it returns None.
Example
fn main() {// create some stringslet str1 = "Educative is the best platform!";let str2 = "Rust";let str3 = "Welcome to Edpresso";let str4 = "Programming";// create the matcheslet match1 = "is";let match2 = 'R';let match3 = "to";let match4 = "23";// find the matches and print byte indicesprintln!(" {:?}", str1.find(match1));println!(" {:?}", str2.find(match2));println!(" {:?}", str3.find(match3));println!(" {:?}", str4.find(match4));}
Explanation
- Lines 3–6: We create some strings.
- Lines 9–12: We create some more strings that we will search for in the strings created in lines 3–6.
- Lines 15–18: We use the
find()method to check if any matches were found and print the results to the console screen.