14

Given the following two strings:

let subject: &str = "zoop-12";
let trail: &str "-12";

How would I go about removing trail from subject only once? I would only like to do this in the case that subject has these characters at its end, so in a case like this I would like nothing removed:

let subject: &str "moop-12loop";
let not_a_trail: &str = "-12";

I'm okay with either being a String or &str, but I choose to use &str for brevity.

2 Answers 2

10

There is also str::strip_suffix

fn remove_suffix<'a>(s: &'a str, suffix: &str) -> &'a str {

    match s.strip_suffix(suffix) {
        Some(s) => s,
        None => s
    }
}

fn main() {
    let subject: &str = "zoop-12";
    //let subject: &str = "moop-12loop";
    let trail: &str = "-12";

    let stripped_subject = remove_suffix(subject, trail);
    
    println!("{}", stripped_subject);
}
Sign up to request clarification or add additional context in comments.

Comments

7

Your specification is very similar to trim_end_matches, but you want to trim only one suffix whereas trim_end_matches will trim all of them.

Here is a function that uses ends_with along with slicing to remove only one suffix:

fn remove_suffix<'a>(s: &'a str, p: &str) -> &'a str {
    if s.ends_with(p) {
        &s[..s.len() - p.len()]
    } else {
        s
    }
}

The slice will never panic because if the pattern matches, s[s.len() - p.len()] is guaranteed to be on a character boundary.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.