Start learning free

LESSON 169 OF 413 · PROJECTS: EVERYDAY PROGRAMS

Password Strength V3 - Character Classes in C#

Practice

Track four boolean flags for a password: does it contain an uppercase letter, a lowercase letter, a digit, and a symbol (non-alphanumeric)?

You start with:

string password = "Secret!99";

Build:

Length: 9
Upper: True
Lower: True
Digit: True
Symbol: True
Strong

Rules:

  • Print "Length: " followed by the number of characters.
  • Start four flags (hasUpper, hasLower, hasDigit, hasSymbol) at false. Loop over every character and set the matching flag to true.
  • A symbol is any character that is not a letter and not a digit.
  • Print one line per flag, in this order: "Upper: ", "Lower: ", "Digit: ", "Symbol: ", each followed by the flag. Write it as True or False with a capital letter, exactly as in the example (your language's own boolean prints differently, so choose the text yourself).
  • If the length is at least 8 and all four flags are true (stricter than the last lesson), print Strong; otherwise print Weak.

Try other passwords: with secret99 the output is

Length: 8
Upper: False
Lower: True
Digit: True
Symbol: False
Weak

Use char.IsUpper(c), char.IsLower(c), char.IsDigit(c) and char.IsLetterOrDigit(c) inside foreach (char c in password).

string password = "Secret!99";

int length = password.Length;
Console.WriteLine("Length: " + length);
bool hasUpper = false;
bool hasLower = false;
bool hasDigit = false;
bool hasSymbol = false;
foreach (char c in password) {
    if (char.IsUpper(c)) {
        hasUpper = true;
    }
    if (char.IsLower(c)) {
        hasLower = true;
    }
    if (char.IsDigit(c)) {
        hasDigit = true;
    }
    if (!char.IsLetterOrDigit(c)) {
        hasSymbol = true;
    }
}
Console.WriteLine("Upper: " + (hasUpper ? "True" : "False"));
Console.WriteLine("Lower: " + (hasLower ? "True" : "False"));
Console.WriteLine("Digit: " + (hasDigit ? "True" : "False"));
Console.WriteLine("Symbol: " + (hasSymbol ? "True" : "False"));
if (length >= 8 && hasUpper && hasLower && hasDigit && hasSymbol) {
    Console.WriteLine("Strong");
} else {
    Console.WriteLine("Weak");
}

STEP 1 OF 13
    Ctrl + Enter to check

    Password Strength V3 in C#

    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free