Trim Whitespace with trim()
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
Trim both sides
Trim tabs and newlines
All whitespace becomes empty
Internal spaces preserved
No whitespace, unchanged
Algorithm Flow

Solution Approach
Best Answers
fn solution(s: &str) -> String {
s.trim().to_string()
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
