Rust - 检查字符串是否以一组子字符串中的一个开头的惯用方法

Jac*_*eth 1 string rust

core::str
pub fn starts_with<'a, P>(&'a self, pat: P) -> bool
where
    P: Pattern<'a>,
Run Code Online (Sandbox Code Playgroud)

如果给定模式与此字符串切片的前缀匹配,则返回 true。

如果不存在则返回 false。

该模式可以是&str[char]、 s 的切片[char]、或者确定字符是否匹配的函数或闭包。

查看字符串是否以一组子字符串中的一个开头的惯用方法是什么?

if applesauce.starts_with(['a', 'b', 'c', 'd']) {
    // elegant if you're looking to match a single character
}

if applesauce.starts_with("aaa") || applesauce.starts_with("bbb") || applesauce.starts_with("ccc") || applesauce.starts_with("ddd") {
    // there *must* be a better way!
}
Run Code Online (Sandbox Code Playgroud)

Cha*_*man 5

您可以使用迭代器:

if ["aaa", "bbb", "ccc", "ddd"].iter().any(|s| applesauce.starts_with(*s)) {
    // there *must* be a better way!
}
Run Code Online (Sandbox Code Playgroud)