Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

rust
communitycreator

How can we check if a string starts with a sub-string in Rust

okwudili onyejiaku

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 of string.

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 strings
  let str1 = "Edpresso";
  let str2 = "Educative";
  let str3 = "Rust";
  let str4 = "Educative is the best platform!";

  // create strings to check
  let start1 = "Ed";
  let start2 = "cative";
  let start3 = "R";
  let start4 = "Educative is";

  // check if strings starts with the sub-strings
  println!(" {} 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));
}
Check if a string starts with a particular sub-string in Rust

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.

RELATED TAGS

rust
communitycreator
RELATED COURSES

View all Courses

Keep Exploring