如何检查字符串是否只包含 Rust 中的字符集? [英] How to check if string only contains set of characters in Rust?
本文介绍了如何检查字符串是否只包含 Rust 中的字符集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Rust 中检查字符串是否仅包含特定字符集的惯用方法是什么?
What is the idiomatic way in Rust to check if a string only contains a certain set of characters?
推荐答案
您可以使用 all
来检查所有字符是否都是字母数字.
You'd use all
to check that all characters are alphanumeric.
fn main() {
let name = String::from("Böb");
println!("{}", name.chars().all(char::is_alphanumeric));
}
chars
返回一个字符迭代器.all
如果函数对迭代器的所有元素都为真,则 a> 返回真.is_alphanumeric
检查其是否为字母数字.
对于任意字符集,您可以将您喜欢的任何函数或代码块传递给all
.
For arbitrary character sets you can pass whatever function or code block you like to all
.
有趣的是,str
上的相应方法被明确删除了微妙的 Unicode 原因.
Interestingly, the corresponding methods on str
were explicitly removed for subtle Unicode reasons.
这篇关于如何检查字符串是否只包含 Rust 中的字符集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文