← 中文资源

简体中文版本

按字符类统计文本构成

用 char 的 is_ascii_digit/is_ascii_alphabetic/is_whitespace 把每个字符归入四类计数,bool as usize 累加,余量即符号。

阅读英文原文

实现说明

按字符类统计文本构成的核心是函数 from_text、has_password_shape、main。 重复被限制在 for ch in text.chars() 里——其余代码按顺序各跑一遍。

使用要点

  • 跑完文件,输出里会留下标记——user123! strong:、hello strong:。
  • 执行文件,main 会按顺序走完 from_text、has_password_shape。

常见问题

运行「按字符类统计文本构成」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 user123! strong:、hello strong: 这类标签。

主签名形如 fn from_text(text: &str) -> Self

核心语句

counts.letters += ch.is_ascii_alphabetic() as usize;
counts.whitespace += ch.is_whitespace() as usize;
counts.digits += ch.is_ascii_digit() as usize;

代码示例

#[derive(Debug, Default, PartialEq)]
struct CharCounts {
    digits: usize,
    letters: usize,
    whitespace: usize,
    symbols: usize,
}

impl CharCounts {
    // bool as usize 把判定结果直接累加成计数
    fn from_text(text: &str) -> Self {
        let mut counts = CharCounts::default();
        for ch in text.chars() {
            counts.digits += ch.is_ascii_digit() as usize;
            counts.letters += ch.is_ascii_alphabetic() as usize;
            counts.whitespace += ch.is_whitespace() as usize;
        }
        // 其余全是符号:总数减去已知三类
        counts.symbols = text.chars().count()
            - counts.digits
            - counts.letters
            - counts.whitespace;
        counts
    }

    // 形状检查:三类齐全才算强口令候选
    fn has_password_shape(&self) -> bool {
        self.letters > 0 && self.digits > 0 && self.symbols > 0
    }
}

fn main() {
    for sample in ["user123!", "   ", "hello", "ab-9"] {
        let counts = CharCounts::from_text(sample);
        println!("{sample:?} -> {counts:?}");
    }

    println!("user123! strong: {}", CharCounts::from_text("user123!").has_password_shape());
    println!("hello    strong: {}", CharCounts::from_text("hello").has_password_shape());
}