Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

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.

like image 436
Newbyte Avatar asked Dec 13 '19 22:12

Newbyte


2 Answers

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.

like image 132
trent Avatar answered Oct 12 '22 05:10

trent


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);
}
like image 31
User Avatar answered Oct 12 '22 06:10

User