Problem overview
The password checker now has two rules. A password is Strong only if it has at least 8 characters and contains at least one digit. Otherwise it is Weak. The program prints three lines: the length, whether a digit was found, and the verdict.
For "Secret99" the output is:
Length: 8
Has digit: True
Strong
The length is 8, the last two characters are digits, and both rules pass. For "abcdefgh" the length is still 8, but there is no digit, so the lines are Length: 8, Has digit: False and Weak.
Approach: a flag set by a loop
The length is easy: password.Length. Finding out whether the password contains a digit takes a loop, because the answer depends on every character.
The standard tool here is a flag: a bool variable that starts at false, meaning "no digit seen yet". The loop looks at each character, and whenever it finds a digit it sets the flag to true. Nothing in the loop ever sets the flag back to false, so one digit anywhere is enough to leave it true at the end. If the loop finishes and the flag is still false, no character was a digit.
After the loop, the two rules are combined with && (and): both must be true for Strong, and anything else is Weak.
Step by step
- Store the length in an
intnamedlengthand print the first line. - Create the flag.
hasDigitis aboolthat starts atfalse. - Loop over the characters. A
foreachwith acharvariablechands the loop one character ofpasswordper round. - Test each character. Inside the loop, an
ifaskschar.IsDigit(c). When it is true, the flag becomestrue. - Print the flag after the loop. The line goes outside the braces, so it runs once, when every character has been checked.
- Write the verdict. The condition
length >= 8 && hasDigitselectsStrong. - Add the
else. It catches every other case: too short, no digit, or both.
The solution in C#
string password = "Secret99";
int length = password.Length;
Console.WriteLine("Length: " + length);
bool hasDigit = false;
foreach (char c in password) {
if (char.IsDigit(c)) {
hasDigit = true;
}
}
Console.WriteLine("Has digit: " + (hasDigit ? "True" : "False"));
if (length >= 8 && hasDigit) {
Console.WriteLine("Strong");
} else {
Console.WriteLine("Weak");
}
The C# details worth a closer look:
foreachover a string. Astringcan be walked like a collection ofcharvalues. The loop variable is read-only:c = 'x';inside the loop is a compile error, becausecis a foreach iteration variable.- Single quotes and double quotes.
'7'is achar, one character, while"7"is astring.char.IsDigittakes achar. - The ternary operator.
hasDigit ? "True" : "False"picks the first text whenhasDigitis true and the second when it is false. The parentheses around it matter. Written as"Has digit: " + hasDigit ? "True" : "False", the+is evaluated first, which leaves astringas the condition, and the compiler rejects it with Cannot implicitly convert type 'string' to 'bool'. - A
boolalready prints asTrue. In C#,"Has digit: " + hasDigitproducesHas digit: TrueorHas digit: False, with capital letters. The ternary spells out the text so the output doesn't depend on that formatting, and it is the pattern for printing any wording you choose, such asYesandNo. &&short-circuits. Iflength >= 8is false, C# does not look athasDigit, because the whole condition is already false. Here that changes nothing, sincehasDigitis a plain variable, but it matters when the right side is a method call.
Stopping early and shorter forms
Once a digit is found, the remaining characters can't change the answer. Adding break; after hasDigit = true; ends the loop at that point. For "Secret99" the loop would stop at the first 9, the seventh character, instead of visiting all eight. The lesson's version keeps the plain loop, which is simpler to read and costs nothing noticeable on a short text. C# also has a one-line form, password.Any(char.IsDigit), from the System.Linq namespace, but the explicit loop shows what that call does.
What counts as a digit
char.IsDigit is true for the decimal digits of any writing system, not only 0 to 9. For example, char.IsDigit('٣') (the Arabic-Indic digit three) is true. For this lesson that is fine. If you ever need to accept only the ASCII digits, test the range instead: c >= '0' && c <= '9'.
Edge cases and common mistakes
- Long but no digit.
"abcdefgh"passes the length rule and fails the digit rule, so it isWeak. - Digit but short.
"a1"has a digit and a length of 2, so it isWeak. - Resetting the flag in the loop. An
else { hasDigit = false; }would let the last character decide the answer, and"1abcdefg"would be reported as having no digit. The flag only ever changes in one direction. - Printing inside the loop. A
Console.WriteLinefor the flag inside the braces would print once per character, eight lines for an 8-character password. - Using
||instead of&&. That would call a password strong when it satisfies either rule, so"abcdefgh"would beStrong. - Empty password.
""never enters the loop, sohasDigitstaysfalseand the output isLength: 0,Has digit: False,Weak.
Testing
"Secret99"givesLength: 8,Has digit: True,Strong."abcdefgh"givesLength: 8,Has digit: False,Weak."a1"givesLength: 2,Has digit: True,Weak."1abcdefg"givesLength: 8,Has digit: True,Strong.
