To trim a string in Rust, you can use the trim()
, trim_start()
, and trim_end()
methods of the str type.
In this example,
" Hello World "
to the variable str1
.trim()
method on str1
to remove leading and trailing whitespace characters.fn main() {
let str1 = " Hello World ";
let trimmed_str1 = str1.trim();
println!("Trimmed string is: '{}'", trimmed_str1);
}
Trimmed string is: 'Hello World'
In this example,
" apple"
to the variable str2
.trim_start()
method on str2
to remove leading whitespace characters.fn main() {
let str2 = " apple";
let trimmed_str2 = str2.trim_start();
println!("Trimmed string is: '{}'", trimmed_str2);
}
Trimmed string is: 'apple'
In this example,
"banana "
to the variable str3
.trim_end()
method on str3
to remove trailing whitespace characters.fn main() {
let str3 = "banana ";
let trimmed_str3 = str3.trim_end();
println!("Trimmed string is: '{}'", trimmed_str3);
}
Trimmed string is: 'banana'
In this tutorial, we learned How to Trim a String in Rust language with well detailed examples.