Count Char Classes In Text
Bucket every character of a password candidate into digit, letter, whitespace, and symbol counts using char classification methods.
Code
#[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());
}How it works
Count Char Classes In Text comes down to the functions from_text, has_password_shape and main.
A single loop drives the file — for ch in text.chars().
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
Using it
Signature: fn from_text(text: &str) -> Self
Running the file prints labeled results such as user123! strong:, hello strong: — each operation’s effect is visible in the output.
Running the file executes main, which drives from_text and has_password_shape in order.
Key statements
counts.letters += ch.is_ascii_alphabetic() as usize;
counts.whitespace += ch.is_whitespace() as usize;
counts.digits += ch.is_ascii_digit() as usize;
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- What does Count Char Classes In Text print when run?
- The script runs standalone; its 2 labeled outputs include `user123! strong:`, `hello strong:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.