Remove whitespace: trim, strip in Rust

trim trim_start trim_end strip rstrip lstrip

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.

examples/trim/src/main.rs

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

'

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo