[英]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?我将如何只从
subject
删除一次trail
? 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:我只想在
subject
末尾有这些字符的情况下执行此操作,因此在这种情况下,我不希望删除任何内容:
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.我可以接受
String
或&str
,但为了简洁起见,我选择使用&str
。
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.您的规范与
trim_end_matches
非常相似,但您只想修剪一个后缀,而trim_end_matches
将修剪所有后缀。
Here is a function that uses ends_with
along with slicing to remove only one suffix:这是一个使用
ends_with
和切片来仅删除一个后缀的函数:
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.切片永远不会恐慌,因为如果模式匹配,
s[s.len() - p.len()]
保证在字符边界上。
There is also str::strip_suffix还有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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.