Start learning free

LESSON 201 OF 293 · PROJECTS: EVERYDAY PROGRAMS

Password Strength V4 in Rust: Counting Character Classes

Practice Read the full explanation

Count how many characters of each class the password contains.

You start with:

The Rust editor starts empty, so write the whole program yourself. Begin with the data:

let password = "Hello!World9";

Build:

Uppercase: 2
Lowercase: 8
Digits: 1
Symbols: 1

Rules:

  • Use four integer counters, all starting at 0.
  • Loop through each character and add 1 to the matching counter.
  • Treat any character that is not a letter and not a digit as a symbol.
  • Print one line per counter, in this order: "Uppercase: ", "Lowercase: ", "Digits: ", "Symbols: ", each followed by the count.

Try other passwords: with Pass word!2 the output is

Uppercase: 1
Lowercase: 7
Digits: 1
Symbols: 2

c.is_ascii_uppercase(), c.is_ascii_lowercase(), c.is_ascii_digit(), c.is_ascii_alphanumeric() with += 1.

let password = "Hello!World9";

let mut uppercase = 0;
let mut lowercase = 0;
let mut digits = 0;
let mut symbols = 0;
for character in password.chars() {
    if character.is_ascii_uppercase() {
        uppercase += 1;
    }
    if character.is_ascii_lowercase() {
        lowercase += 1;
    }
    if character.is_ascii_digit() {
        digits += 1;
    }
    if !character.is_ascii_alphanumeric() {
        symbols += 1;
    }
}
println!("Uppercase: {}", uppercase);
println!("Lowercase: {}", lowercase);
println!("Digits: {}", digits);
println!("Symbols: {}", symbols);

STEP 1 OF 14
    Ctrl + Enter to check

    RUST · PROJECTS: EVERYDAY PROGRAMS

    Password Strength V4 in Rust, explained

    Problem overview

    Version 4 stops asking "is there one?" and asks "how many?". For the password Hello!World9 the program prints how many uppercase letters, lowercase letters, digits and symbols it contains:

    Uppercase: 2
    Lowercase: 8
    Digits: 1
    Symbols: 1
    

    A symbol is any character that is neither a letter nor a digit, a space included. For Pass word!2 the output is Uppercase: 1, Lowercase: 7, Digits: 1, Symbols: 2: the space and the !.

    Approach: counters instead of flags

    The structure of version 3 stays: one pass over the characters with one test per class. The change is what each test does. A flag is set with = true, while a counter is increased with += 1. So the four booleans become four integers starting at 0, and the verdict logic disappears: this version only reports the counts.

    Step by step

    1. Create password with the text "Hello!World9".
    2. Create uppercase with let mut, set to 0.
    3. Create lowercase the same way.
    4. Create digits the same way.
    5. Create symbols the same way.
    6. Loop with for character in password.chars(). For this password it runs 12 times.
    7. Uppercase test: character.is_ascii_uppercase(), then uppercase += 1.
    8. Lowercase test: character.is_ascii_lowercase(), then lowercase += 1.
    9. Digit test: character.is_ascii_digit(), then digits += 1.
    10. Symbol test: !character.is_ascii_alphanumeric(), then symbols += 1.
    11. Print the four lines after the loop, in the order Uppercase, Lowercase, Digits, Symbols.

    The solution in Rust

        let password = "Hello!World9";
    
        let mut uppercase = 0;
        let mut lowercase = 0;
        let mut digits = 0;
        let mut symbols = 0;
        for character in password.chars() {
            if character.is_ascii_uppercase() {
                uppercase += 1;
            }
            if character.is_ascii_lowercase() {
                lowercase += 1;
            }
            if character.is_ascii_digit() {
                digits += 1;
            }
            if !character.is_ascii_alphanumeric() {
                symbols += 1;
            }
        }
        println!("Uppercase: {}", uppercase);
        println!("Lowercase: {}", lowercase);
        println!("Digits: {}", digits);
        println!("Symbols: {}", symbols);
    

    Rust details worth knowing:

    • The counters are i32. With no other type information, the literal 0 makes each counter an i32, which is plenty for a password.
    • += 1 needs mut. Without it, the compiler rejects the assignment because the variable is immutable.
    • One println! per line. Each {} takes the next value, and println! ends the line.
    • The ASCII methods and other alphabets. is_ascii_uppercase() and is_ascii_lowercase() know only A to Z and a to z. For é1 the output is Uppercase: 0, Lowercase: 0, Digits: 1, Symbols: 1: the accented letter is not in any letter class, so it lands in the symbol count.
    • The counts add up here. Every ASCII character falls into exactly one of the four classes, so the four counts sum to the number of characters. That makes a handy check: 2 + 8 + 1 + 1 is 12 for Hello!World9.

    Tracing the counters

    For the short password Ab1! the counters change like this, one character at a time:

    A -> uppercase=1 lowercase=0 digits=0 symbols=0
    b -> uppercase=1 lowercase=1 digits=0 symbols=0
    1 -> uppercase=1 lowercase=1 digits=1 symbols=0
    ! -> uppercase=1 lowercase=1 digits=1 symbols=1
    

    Every character increases exactly one counter. The four lines of output are the counters' final values, which is why the printing happens once, after the loop has finished.

    Compared with version 3, nothing about the loop's shape changed. Only the action inside each if did: a counter can say "three digits", where a flag could only say "at least one".

    Two other ways to count

    Rust can count the characters that pass a test without a loop of your own:

    let uppercase = password.chars().filter(|c| c.is_ascii_uppercase()).count();
    let lowercase = password.chars().filter(|c| c.is_ascii_lowercase()).count();
    

    For Hello!World9 these give 2 and 8, matching the counters. The cost is one pass per class instead of one pass in total, which is irrelevant for a password but worth knowing for large inputs.

    A match on character ranges classifies each character with a single test:

    for ch in password.chars() {
        match ch {
            'A'..='Z' => uppercase += 1,
            'a'..='z' => lowercase += 1,
            '0'..='9' => digits += 1,
            _ => symbols += 1,
        }
    }
    

    Here _ catches everything else, and the four counts for Hello!World9 come out as 2, 8, 1 and 1. The lesson uses separate if statements because they follow the wording of the task one rule at a time.

    The compiler error for a missing mut

    Forgetting mut is the most common slip in this kind of program. Declaring let uppercase = 0; and then writing uppercase += 1; in the loop fails to compile, with this message:

    error[E0384]: cannot assign twice to immutable variable `uppercase`
    

    The compiler's own suggestion is to write let mut uppercase = 0;. The same applies to every counter and flag in this project: a variable that changes inside a loop needs mut, and one that never changes does not.

    What counts as a symbol

    The symbol rule is a catch-all. It does not list punctuation marks; it says that whatever is not a letter and not a digit is a symbol. That is why a space counts, and why characters outside the English alphabet end up there too. The é in é1 is a letter to a person, but is_ascii_lowercase() only recognizes a to z, so the character falls through to !is_ascii_alphanumeric() and is counted as a symbol.

    If you want accented letters counted as letters, Rust has methods that understand all of Unicode, is_lowercase() and is_alphanumeric(). This lesson sticks to the ASCII methods, which match its task exactly for ordinary passwords.

    Edge cases and common mistakes

    • Using else if for the last test. It would still work for ASCII text, but separate if statements make each class independent.
    • Printing inside the loop. That would print the lines once per character instead of once at the end.
    • Forgetting the ! on the symbol test. The symbols counter would then count letters and digits.
    • Spaces. A space is a symbol, not ignored.
    • Empty password. Every counter stays 0.
    • Only symbols. !!! gives Symbols: 3 and zeros elsewhere.

    Testing

    PasswordUppercaseLowercaseDigitsSymbols
    Hello!World92811
    Pass word!21712
    !!!0003
    (empty)0000
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free