What is the trim function in Rust?

trim() is a built-in function in Rust used to trim leading and trailing whitespaces in a string.

//trim() function returns a string slice after removing the whitespaces 
pub fn trim(&self) -> &str 

Different trim() functions

trim_start() returns the string slice after removing the leading whitespace.

trim_end() returns the string slice after removing the trailing whitespace.

Note: The two functions, trim_left() and trim_right() were previously used to remove leading and trailing whitespaces, but have been superseded with trim_start() and trim_end() respectively.

trim_matches() returns the string slice after removing the prefixes and suffixes that repeatedly match some pattern.

The pattern can be a single char, chars slice, a function, or a closureused to determine whether the character matches or not.

//DoubleEndedSearcher
pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str
where
    P: Pattern<'a>,
    <P as Pattern<'a>>::Searcher: DoubleEndedSearcher<'a>,

trim_start_matches() returns the string slice after removing all the prefixes that repeatedly match some pattern.

trim_end_matches() returns the string slice after removing all the suffixes that repeatedly match some pattern.


Code example

fn main() {
let test = " 1Rust program1 ";
println!("INITIALLY STRING LENGTH IS, {}", test.len());
println!("{:?}", test); //debug placeholder
println!();
//trim()
println!("After trim(), string length is {}", test.trim().len());
println!("{:?}", test.trim());
println!();
//trim_start()
println!("After trim_start(), string length is {}", test.trim_start().len());
println!("{:?}", test.trim_start());
println!();
//trim_end()
println!("After trim_end(), string length is {}", test.trim_end().len());
println!("{:?}", test.trim_end());
println!();
//trim_end_matches()
println!("With trim_end_matches(), string 23Rust program23 becomes");
println!("{:?}", "23Rust program23".trim_end_matches("23"));
println!();
//trim_start_matches()
println!("With trim_start_matches(), string 23Rust program23 becomes");
println!("{:?}", "23Rust program23".trim_start_matches("23"));
println!();
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved