Rust Reference ยท Strings and Text
Rust str::trim and strip_prefix
Reference for Rust str::trim, trim_start, trim_end, trim_matches, strip_prefix and strip_suffix: what counts as whitespace, patterns and Option results.
str::trim returns a slice of the string without leading and trailing whitespace. It does not change the original and does not allocate: the result is just a narrower view into the same bytes. trim_start and trim_end remove only one side.
For removing something other than whitespace, use trim_matches (any characters from a pattern, repeatedly) or strip_prefix and strip_suffix (exactly one occurrence, returning an Option so you know whether it was there).
let clean = " hello \n".trim(); assert_eq!(clean, "hello");
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
fn trim(&self) -> &str fn trim_start(&self) -> &str fn trim_end(&self) -> &str fn trim_matches<P: Pattern>(&self, pat: P) -> &str fn trim_start_matches<P: Pattern>(&self, pat: P) -> &str fn trim_end_matches<P: Pattern>(&self, pat: P) -> &str fn strip_prefix<P: Pattern>(&self, prefix: P) -> Option<&str> fn strip_suffix<P: Pattern>(&self, suffix: P) -> Option<&str>
| Name | Description |
|---|---|
pat |
A char, &str, char array/slice or char closure. trim_matches needs a pattern that can match from both ends, so a multi-character &str is not accepted there. |
prefix, suffix |
The text to remove once from the start or end. |
Returns: a sub-slice of self. strip_prefix and strip_suffix return None when the text does not start or end with the pattern.
Errors / panics / edge cases: none panic. Trimming a string that is all whitespace gives "".
Usage notes
trimremoves Unicode whitespace as defined bychar::is_whitespace: spaces, tabs,\n,\r, non-breaking space and others. It never touches whitespace in the middle.trim_leftandtrim_rightare deprecated names fortrim_startandtrim_end; the new names are direction-neutral for right-to-left text.trim_*_matchesrepeats;strip_*removes once."aaab".trim_start_matches('a')is"b", while"aaab".strip_prefix('a')isSome("aab").- Prefer
strip_prefixtostarts_withplus slicing. It does both steps and cannot slice at a wrong index. - Lines read from input end with
\n. Calltrim_end()(ortrim()) before parsing a number read withread_line, otherwiseparsefails. - The result borrows
self. Use.to_string()or.to_owned()to get an ownedString; to trim aStringin place you must reassign or truncate it. - Cost:
O(k)in the number of characters removed; no copying.