简体   繁体   中英

How do I remove a single trailing string from another string in Rust?

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.

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM