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

Overview

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.

Syntax

This is the syntax of the trim() method:

string.trim()
Syntax of the trim() method of a string in Rust

Parameter value

string: This is the string we want to trim to remove its leading and trailing whitespace characters.

Example

Let’s look at the code example given below:

fn main() {
// create some strings
let string1 = " Welcome to Edpresso ";
let string2 = "Educative is the best! ";
let string3 = " Rust is very interesting!";
// trim the strings
let trim1 = string1.trim();
let trim2 = string2.trim();
let trim3 = string3.trim();
// print the trims
println!("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());
}

Explanation

  • Lines 3–5: We create some strings.
  • Lines 8–9: We trim the strings and save the results.
  • Lines 13–20: We print the results to the console.