我能做到这一点没有任何问题:
"hello".ends_with("o"); //true但是,我想将这一行的末尾与几个变体进行比较:
let endings = vec!["o", "a"];
fn check_str(s: &str, e: Vec<&str>) -> bool {
s.ends_with(e)
}
check_str("some...", endings); //true or false在不使用for迭代数组或向量的情况下,可以做到这一点吗?
发布于 2022-09-02 07:23:34
可以做到这一点,而不需要迭代数组或向量的for?
视情况而定。
如果您只是在寻找单个字符,那么是的:str::ends_with的签名是
pub fn ends_with<'a, P>(&'a self, pat: P) -> bool where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>, 这意味着实现Pattern的任何东西都能工作。Pattern是一个不稳定的API,因此您只能得到标准库实现的内容,即:
包含在string
char ->的真正)
最后一个是你的"in":
fn main() {
let endings = vec!['o', 'a'];
for s in &["some...", "strings", "ends", "with", "carbonara"] {
dbg!(s.ends_with(endings.as_slice()));
}
}如果您需要更复杂的东西(例如,多个实际子字符串),那么迭代是您唯一的选择。
但这并不意味着你有
使用for对数组或向量进行迭代?
铁锈对迭代器有很好的支持,所以您可以编写如下内容:
endings.iter().any(|n| s.ends_with(*n))这将返回真/假,这取决于s,以endings的任何值结尾。
发布于 2022-09-02 07:22:45
如果您不想自己使用for进行迭代,您可以使用函数样式,但是它会在内部迭代。
fn check_str(
s: &str,
endings: &[&str],
) -> bool {
endings.iter().any(|e| s.ends_with(e))
}
fn main() {
let endings = vec!["o", "a"];
println!("{}", check_str("some...", &endings));
println!("{}", check_str("hello", &endings));
println!("{}", check_str("voila", &endings));
}
/*
false
true
true
*/https://stackoverflow.com/questions/73579025
复制相似问题