Start learning free

LESSON 69 OF 414 · STRINGS I

String Strip in Rust: Trimming with trim()

Lesson Read the full explanation

In Rust, the built-in .trim() method removes leading and trailing whitespace from a string:

// trim() removes leading and trailing spaces
let s = "  hello  ";
let result = s.trim();
// result == "hello"

Here is an example showing how .trim() works:

let s = "  hello  ";
let result = s.trim();
println!("{}", result); // hello

Assignment
Follow the Coding Tutorial and use .trim() to strip whitespace from s!


Hint
Use s.trim() and assign the result to result.

STEP 1 OF 1
    Ctrl + Enter to check

    RUST · STRINGS I

    String Strip in Rust, explained

    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) and strip_suffix(p) remove an exact piece of text from one end, but return an Option, because the text might not be there: "prefix-name".strip_prefix("prefix-") is Some("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, and s is 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:

    1. Declare s holding " hello ", with two spaces on each side.
    2. Declare result and assign it s.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 &str borrowed from the original, so the original is unchanged.
    • trim_start() and trim_end() work on one side; trim_matches removes chosen characters.
    • Whitespace inside the text stays as it is.
    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free