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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With