Trim End Matches Strips Repeated Runs

trim_end_matches strips repeated suffix matches until none remains, so trailing separators and repeated runs vanish in one call, unlike one-shot strip_suffix.

RustData Integrity

Code

rustsnippet
14 lines
fn main() {
    // repeated runs: trim_end_matches strips until no match remains, not just once
    let bases = ["https://api.example.com/v1/", "docs/guide///", "root"];
    for base in bases {
        println!("{base} -> {}", base.trim_end_matches('/'));
    }

    let noisy = "report final draft draft";
    println!("{noisy} -> {}", noisy.trim_end_matches(" draft"));

    // trim_start_matches works the same way on the left side
    let zeroed = "00042";
    println!("{zeroed} -> {}", zeroed.trim_start_matches('0'));
}

What the demo trims

Three URL-shaped bases go through trim_end_matches on the slash character: the first loses its trailing slash, docs/guide/// loses all three at once, and root, with nothing to strip, prints unchanged. Repeated runs disappear in one call because the trim repeats until no match remains.

The repeated word gets the same treatment: trim_end_matches(” draft”) strips both trailing copies of the phrase, printing report final. trim_start_matches then works the left side, turning 00042 into 42 while the leading zeros all fall away.

Caveats and details

  • strip_suffix removes exactly one occurrence; trim_end_matches repeats.
  • The pattern can be a char, a str slice, or a closure.

Interactive Tools for This Topic

FAQ

How does this differ from strip_suffix?
strip_suffix removes one suffix at most; trim_end_matches keeps stripping while the tail still matches, which is why the three slashes vanish together.