What is strip_prefix() in Rust?

Overview

The strip_prefix() method is used to strip or remove a starting string or prefix of a string. It returns the slice with the specified prefix removed from the original string. This method returns the sub-string after the prefix that is wrapped by Some. If the specified prefix does not start the string then it is a None.

Syntax

string.split_prefix(prefix)
Syntax for split_prefix() method in Rust

Parameters

string: This is the string that we want to remove a prefix of.

prefix: This is the prefix 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 prefixes
println!("Stripping {:?} from {} = {:?}","Ed",str1, str1.strip_prefix("Ed"));
println!("Stripping {:?} from {} = {:?}","cative",str2, str2.strip_prefix("cative"));
println!("Stripping {:?} from {} = {:?}","R",str3, str3.strip_prefix("R"));
println!("Stripping {:?} from {} = {:?}","Educative is",str4, str4.strip_prefix("Educative is"));
}

Explanation

  • Line 3–6: We create some strings. These are the strings that we want to remove a prefix of.
  • Lines 9–12: We strip or remove prefixes from the strings using the strip_prefix() method. Then we print the results to the console.

Free Resources