Rust Trimming Text
The trim family cleans the edges of text with any pattern. trim() removes whitespace from both ends.
One end at a time
trim_start and trim_end clean a single edge each:
println!("[{}]", " hi ".trim_start());
println!("[{}]", " hi ".trim_end());
println!("[{}]", " hi there \t\n".trim());trim_matches takes any pattern
A char, a set of chars, or a test — the pattern idea from the last lesson, at the edges:
println!("{}", "--hello--".trim_matches('-'));
println!("{}", "xyxhelloxyx".trim_matches(&['x', 'y'][..]));
println!("{}", "123hello321".trim_matches(char::is_numeric));Trimming repeats
trim_start_matches keeps stripping while the pattern matches at that edge:
println!("{}", "abcabcabcX".trim_start_matches("abc"));
println!("{}", "hello!!!".trim_end_matches('!'));strip takes one piece, or says None
strip_prefix removes one exact start and reports honestly when it is missing:
println!("{:?}", "file.txt".strip_prefix("file"));
println!("{:?}", "file.txt".strip_prefix("data"));
println!("{:?}", "photo.png".strip_suffix(".png"));
println!("{:?}", "#tag".strip_prefix('#'));Example
fn main() {
let raw = " ## Weekly Report ## ";
let title = raw.trim().trim_matches('#').trim();
println!("title = [{}]", title);
let file = "report.PDF";
let stem = file.strip_suffix(".PDF").unwrap_or(file);
println!("stem = {}", stem);
let tagged = "#rust";
println!("tag = {}", tagged.strip_prefix('#').unwrap_or(tagged));
}Key points
- The trim family only ever cleans edges: the middle of the text is never touched.
- Every trim method returns a &str view of the middle — the original text is not changed, and nothing is copied
- trim removes whitespace: spaces, tabs, new lines and carriage returns, from both ends
- trim_matches takes a pattern (last lesson): it keeps removing while the pattern matches at that edge — not just once
- strip_prefix and strip_suffix remove one exact piece.
- Both strip methods return Option<&str>.
- Some(rest) comes back when the piece was there.
- None comes back when the piece was not there.
- Use trim when the mess is unwanted padding.
- Use strip when one known piece is expected and its absence matters.
In this example, a messy title is cleaned in three chained steps. trim removes the outer spaces. trim_matches('#') removes the hash marks at both edges. A final trim clears the spaces that were hiding under the hashes. The result is Weekly Report. Next, strip_suffix(".PDF") takes the ending off report.PDF. unwrap_or(file) keeps the original name. It keeps it should the ending ever be absent. Last, strip_prefix('#') removes the hash from a tag the same way. Each step is a small view of the text before it — no copies, no changes to the original.
Note
trim works on whitespace only — never letters.
"hello".trim() is still "hello".
For other characters, trimming is trim_matches' job.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What does "data.csv".strip_suffix(".txt") return?