What trim does
Text from users, files and input often carries extra whitespace at its edges: spaces, tabs, line breaks. Many languages call the cleanup operation "strip"; Rust calls it trim. The trim() method removes whitespace from both ends of a string and leaves the middle alone:
let s = " hello ";
let result = s.trim();
println!("[{}]", result);
[hello]
The brackets in the output make the missing spaces visible.
It returns a borrowed slice
trim() doesn't allocate a new string. It returns a &str that points at the part of the original that remains, so result borrows from s. That makes it cheap, and it means s itself still holds all of its spaces. If you need an owned String that can outlive the original, call .to_string() on the result.
What counts as whitespace
Whitespace here means more than the space character. Tabs, newlines and carriage returns count too, along with other Unicode whitespace:
let t = " \t hello \n ";
println!("[{}]", t.trim());
[hello]
This makes trim() the standard way to clean the line ending off text read from input.
Only the edges are touched. In " hello world ", the run of spaces between the words survives:
println!("[{}]", " hello world ".trim());
[hello world]
One side only, or other characters
There are related methods for finer control:
trim_start()removes whitespace from the beginning only.trim_end()removes it from the end only.trim_matches(c)removes a given character from both ends instead of whitespace:"xxhixx".trim_matches('x')is"hi".strip_prefix(p)andstrip_suffix(p)remove an exact piece of text from one end, but return anOption, because the text might not be there:"prefix-name".strip_prefix("prefix-")isSome("name").
The older names trim_left and trim_right are deprecated. Use trim_start and trim_end.
Trimming a String you own
On a String, trim() works too, because a String can be used wherever a &str is expected. The result borrows from the String, so the original must stay alive while you use the trimmed slice. To keep the trimmed text beyond that, turn it into a new owned value with to_string() or String::from.
The length of the result tells you how much was removed: " hello ".len() is 9, and " hello ".trim().len() is 5.
Gotchas
- Ignoring the result.
s.trim();on its own does nothing useful. The trimmed text is the return value, so assign it. - Expecting the string to change. There is no in-place trim on a
&str, andsis unchanged afterwards. - Trimming does not collapse inner spaces. To normalise the spacing between words, combine
split_whitespace()with joining the pieces. - An all-whitespace string becomes empty.
" ".trim()returns"", not an error.
A typical use
Text read from the keyboard or a file usually ends with a line break, which breaks comparisons that look correct. Trimming first fixes that:
let line = "yes\n";
println!("{}", line == "yes");
println!("{}", line.trim() == "yes");
false
true
Trimming is also the first step when you parse a number out of text. Parsing " 42 ".parse::<i32>() fails because of the spaces, while " 42 ".trim().parse::<i32>() succeeds with Ok(42).
Trimming is safe on text with accents or other non-English letters, because trim works on whole characters and never cuts one in half.
Choosing between the trim methods
Start with trim(). Reach for trim_start() or trim_end() when the whitespace on one side is meaningful, for example indentation you want to keep while removing a trailing newline. Reach for strip_prefix or strip_suffix when you must remove an exact piece of text and also need to know whether it was there.
The exercise
This lesson has a single step:
- Declare
sholding" hello ", with two spaces on each side. - Declare
resultand assign its.trim().
let s = " hello ";
let result = s.trim();
After these lines, result is "hello" and s still has its spaces. No mut and no extra memory are involved.
Key takeaways
trim()removes leading and trailing whitespace, including tabs and newlines.- It returns a
&strborrowed from the original, so the original is unchanged. trim_start()andtrim_end()work on one side;trim_matchesremoves chosen characters.- Whitespace inside the text stays as it is.
