Drill

ProblemsC# › validation

Score a password

mediumvalidationStringsC#

The sign-up form shows a strength meter with five segments, one for each rule the password satisfies.

PasswordScore(password: string) → int

C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

public int PasswordScore(string password) {
    
}

Worked examples

CallResult
PasswordScore("abc")1
PasswordScore("abcdefgh")2
PasswordScore("Abcdefg1")4
PasswordScore("Abcdefg1!")5

Hint

Five independent booleans, added up. No early returns.

Reference solution in C#
public int PasswordScore(string password) {
    bool lower = false, upper = false, digit = false, other = false;
    foreach (char c in password) {
        if (c >= 'a' && c <= 'z') lower = true;
        else if (c >= 'A' && c <= 'Z') upper = true;
        else if (c >= '0' && c <= '9') digit = true;
        else other = true;
    }
    int n = password.Length >= 8 ? 1 : 0;
    if (lower) n++;
    if (upper) n++;
    if (digit) n++;
    if (other) n++;
    return n;
}

The same problem in another language

More validation problems in C#