How to remove the spaces and/or newline from the end of a string.
How to remove spaces, tabs from either end of a string?
Rust has the trim_end method to remove any white-space from the end of a string. (right-hand side). The trim_start method to remove the white-spaces from the beginning (left-hand side) of the string.
There used to be a trim_left
and trim_right
but they were replaced by the trim_start
and trim_end
.
trim will remove the white-spaces from both ends of the string.
These will remove spaces, tabs, new-lines from the beginnin or the end of the string.
fn main() {
let text = " text with space inside and outside \t \n\n";
println!("original: '{}'", text);
println!("trim: '{}'", text.trim());
println!("trim_end '{}'", text.trim_end());
println!("trim_start: '{}'", text.trim_start());
}
The result:
$ cargo run -q
original: ' text with space inside and outside
'
trim: 'text with space inside and outside'
trim_end ' text with space inside and outside'
trim_start: 'text with space inside and outside
'