What is string.ends_with() method in Rust?

Overview

The ends_with() method is used to check if a particular substring ends a particular string. For example, with this method, we can check if the string, "Edpresso", ends with "presso".

Syntax

string.ends_with(subString)
Syntax for ends_with() method in Rust

Parameters

  • string: This is the string we want to check if it ends with another string—the substring.
  • subString: This is the substring that we want to check if it ends with the string, string.

Return value

It returns true if the string ends with the specified substring. Otherwise, it returns false.

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 end1 = "presso";
let end2 = "cative";
let end3 = "R";
let end4 = "best platform!";
// check if strings ends with the sub-strings
println!(" {} ends with {}: {}",str1, end1, str1.ends_with(end1));
println!(" {} ends with {}: {}",str2, end2, str2.ends_with(end2));
println!(" {} ends with {}: {}",str3, end3, str3.ends_with(end3));
println!(" {} ends with {}: {}",str4, end4, str4.ends_with(end4));
}

Explanation

  • Lines 3–6: We create some strings.
  • Lines 9–12: We create the substrings we want to check if it ends with the strings we created.
  • Lines 15–18: We use the ends_with() method to check if the strings end with the specified substrings and print the results to the console.

Free Resources