How to check if a string contains a particular match in Rust

Overview

We can use the contains() method of Rust to check if a string contains a particular match or sub-string. It takes only one parameter, which is the sub-string or matches it wants to check.

Syntax

string.contains(substring)
Syntax for contains() method in Rust

Parameters

substring: This is the string we want to check to see if it occurs in another string.

Return value

The value returned is a Boolean value. A true is returned if substring is present, or is contained inside another string. Otherwise, false is returned.

Example

fn main() {
// create some strings
let str1 = "Rust";
let str2 = "Educative is the best platform!";
let str3 = "Welcome to Edpresso";
let str4 = "I am 400 years old";
// check if some substrings are contained in the ones created
println!("{}", str1.contains("ust"));
println!("{}", str2.contains("Educative"));
println!("{}", str3.contains("the"));
println!("{}", str4.contains("400"));
}

Explanation

In the code above:

  • Lines 3–6: We create some strings.
  • Lines 10–13: We check if some sub-strings are present in the strings created, and print the result to the console screen.

Free Resources