【问题标题】:How to check if string only contains set of characters in Rust?如何检查字符串是否仅包含 Rust 中的字符集?
【发布时间】:2018-12-25 18:08:23
【问题描述】:

Rust 中检查字符串是否只包含特定字符集的惯用方法是什么?

【问题讨论】:

    标签: rust text-processing


    【解决方案1】:

    is_alphanumeric()

    fn main() {
        println!("{}", "abcd".chars().all(|x| x.is_alphanumeric()));
    }
    

    【讨论】:

    • s.chars().all(char::is_alphanumeric) 也适用于这种情况。
    • 为了清楚起见,“通用”版本是更改all中的谓词。
    【解决方案2】:

    您可以使用all 来检查所有字符是否都是字母数字。

    fn main() {
        let name = String::from("Böb");
        println!("{}", name.chars().all(char::is_alphanumeric));
    }
    
    • chars 返回一个字符迭代器。
    • all 如果函数对迭代器的所有元素都为真,则返回真。
    • is_alphanumeric 检查其是否为字母数字。

    对于任意字符集,您可以将任何您喜欢的函数或代码块传递给all

    有趣的是,the corresponding methods on str were explicitly removed for subtle Unicode reasons

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-03
      • 2017-12-16
      • 2010-12-19
      • 1970-01-01
      • 1970-01-01
      • 2011-04-04
      • 2014-05-07
      相关资源
      最近更新 更多