Start learning free

LESSON 171 OF 414 · PROJECTS: EVERYDAY PROGRAMS

Password Strength V4 - Count Character Classes in Scala

Practice

Count how many characters of each class the password contains.

You start with:

val 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.isUpper, c.isLower, c.isDigit, c.isLetterOrDigit, with += 1 counters (Scala has no ++).

val password = "Hello!World9"

var uppercase = 0
var lowercase = 0
var digits = 0
var symbols = 0
for (c <- password) {
    if (c.isUpper) {
        uppercase += 1
    }
    if (c.isLower) {
        lowercase += 1
    }
    if (c.isDigit) {
        digits += 1
    }
    if (!c.isLetterOrDigit) {
        symbols += 1
    }
}
println("Uppercase: " + uppercase)
println("Lowercase: " + lowercase)
println("Digits: " + digits)
println("Symbols: " + symbols)

STEP 1 OF 13
    Ctrl + Enter to check

    Password Strength V4 in Scala

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