In Rust, we can use the trim()
method of a string to remove the whitespace characters around that string. This method removes the leading and trailing whitespace characters of a given string.
This is the syntax of the trim()
method:
string.trim()
string
: This is the string we want to trim to remove its leading and trailing whitespace characters.
Let’s look at the code example given below:
fn main() {// create some stringslet string1 = " Welcome to Edpresso ";let string2 = "Educative is the best! ";let string3 = " Rust is very interesting!";// trim the stringslet trim1 = string1.trim();let trim2 = string2.trim();let trim3 = string3.trim();// print the trimsprintln!("The string before trim is '{}' and length is {}", string1, string1.len());println!("The string when trimmed is '{}' and length is {}", trim1, trim1.len());println!("\nThe string before trim is '{}' and length is {}", string2, string2.len());println!("The string when trimmed is '{}' and length is {}", trim2, trim2.len());println!("\nThe string before trim is '{}' and length is {}", string3, string3.len());println!("The string when trimmed is '{}' and length is {}", trim3, trim3.len());}