What is the string.strip_suffix() method in Rust?

Overview

When we want to remove the ending substring or suffix of a string then the strip_suffix() method is required. With this method, the suffix specified (if matched) will be sliced out of the string. It returns the sliced suffix wrapped by Some. If the suffix is not matched or found, then a None is returned.

Syntax

string.split_suffix()
Syntax to remove suffix of a string in Rust

Parameters

string: This is the string whose suffix we want to remove.

suffix: This is the suffix of the string that we want to slice away.

Example

fn main() {
// create some strings
let str1 = "Edpresso";
let str2 = "Educative";
let str3 = "Rust";
let str4 = "Educative is the best platform!";
// strip some suffixes
println!("Stripping {:?} from {} = {:?}","Ed",str1, str1.strip_suffix("Ed"));
println!("Stripping {:?} from {} = {:?}","cative",str2, str2.strip_suffix("cative"));
println!("Stripping {:?} from {} = {:?}","R",str3, str3.strip_suffix("R"));
println!("Stripping {:?} from {} = {:?}","platform!",str4, str4.strip_suffix("platform!"));
}

Explanation

  • Lines 3–6: We create some strings. These are the strings whose suffixes need to be removed.
  • Lines 9–12: We use the strip_suffix() method to remove the suffixes from the strings. Then we print the results to the console.

Free Resources