How can we check if a string starts with a sub-string in Rust
Overview
We can use the starts_with() method to check if a string starts with another string, a sub-string. This method returns true if the string begins with the specified match or sub-string. Otherwise, it returns false.
Syntax
string.starts_with(substring)
Check if a particular string begins with another sub-string in Rust
Parameter values
string: This is the string that we want to check to see if it begins with the specified sub-string.
substring: This is the string that we want to check for at the beginning ofstring.
Return value
The starts_with() method returns a boolean value. It returns a true value if the given string starts with the specified sub-string. Otherwise, it returns a false value.
Example
fn main() {// create some stringslet str1 = "Edpresso";let str2 = "Educative";let str3 = "Rust";let str4 = "Educative is the best platform!";// create strings to checklet start1 = "Ed";let start2 = "cative";let start3 = "R";let start4 = "Educative is";// check if strings starts with the sub-stringsprintln!(" {} starts with {}: {}",str1, start1, str1.starts_with(start1));println!(" {} starts with {}: {}",str2, start2, str2.starts_with(start2));println!(" {} starts with {}: {}",str3, start3, str3.starts_with(start3));println!(" {} starts with {}: {}",str4, start4, str4.starts_with(start4));}
Explanation
- Lines 3–6: We create some strings.
- Lines 9–12: We create the sub-strings that we want to check for at the beginning of the strings we created.
- Lines 15–18: With the
starts_with()method, we check if the strings start with the specified sub-strings and print the results to the console.