Code Logo

Trim Whitespace with trim()

Published at25 Jul 2026
Rust String Handling Easy 0 views
Like0

Write a Rust function that takes a string slice (&str) and returns a new String with leading and trailing whitespace removed using the trim() method. The trim() method returns a &str slice of the input without leading and trailing whitespace characters.

The trim() method in Rust removes whitespace as defined by the Unicode standard, including spaces, tabs, newlines, carriage returns, and other whitespace characters. This is broader than simply removing ASCII spaces. The method returns a borrowed slice (&str) of the original string, making it a zero-copy operation — no new memory is allocated.

Rust also provides trim_start() and trim_end() for one-sided trimming, and trim_matches() for removing specific characters rather than all whitespace. These methods all return borrowed slices rather than owned Strings, which is a key difference from many other languages where trimming creates a new string allocation.

Time complexity is O(n) in the worst case where n is the string length, as the method must scan from both ends to find the first and last non-whitespace characters. Space complexity is O(1) because trim() returns a borrowed slice without allocating.

Edge cases include strings with only whitespace (trim returns empty slice), strings with no whitespace (returns the original slice unchanged), strings with internal whitespace (internal spaces are preserved, only leading/trailing are removed), and Unicode whitespace characters beyond ASCII.

Example Input & Output

Example 1
Input
" hello "
Output
hello
Explanation

Trim both sides

Example 2
Input
"\t\n rust \t\n"
Output
rust
Explanation

Trim tabs and newlines

Example 3
Input
" "
Output
Explanation

All whitespace becomes empty

Example 4
Input
" a b c "
Output
a b c
Explanation

Internal spaces preserved

Example 5
Input
"abc"
Output
abc
Explanation

No whitespace, unchanged

Algorithm Flow

Recommendation Algorithm Flow for Trim Whitespace with trim()
Recommendation Algorithm Flow for Trim Whitespace with trim()

Solution Approach

fn solution(s: &str) -> String {
    s.trim().to_string()
}

Best Answers

rust - Approach 1
fn solution(s: &str) -> String {
    s.trim().to_string()
}