Nodoodle
Nodoodle

Reputation: 67

Count total numeric characters in a string

I am trying to count the numbers inside a string input in a textfield, here's my code

var num = 0
.
. 
.

let stringArray = password.components(separatedBy: CharacterSet.decimalDigits.inverted)
for item in stringArray {
    if let number = Int(item) {
        print("number: \(number)")
        num += 1
    }
}

if num > 4 {
    print("You Shall Pass!!")
}
else {
    print("You Shall Not Pass!!")
}

But when i print the num, it stays on 1. No matter how many number I input in the textfield, it will always print 1 and "you shall not pass!!"

Upvotes: 3

Views: 945

Answers (3)

vadian
vadian

Reputation: 285072

A different approach:

Remove all non-digit characters with Regular Expression and count the result.

let numberOfDigits = password.replacingOccurrences(of: "[^0-9]", with: "", options: .regularExpression).count

Upvotes: 1

Rizwan
Rizwan

Reputation: 3666

In more swifty approach, you may use filter on password string to identify frequency of numbers in it, like:

var password = "tHis4is5test8,#pass11" // 45811 - 5 numeric characters
let numsFrequency = password.filter {"0"..."9" ~= $0}.count
print(numsFrequency) // 5

OR

you may add this in an Extension to String and use it easily.

extension String {
    var numbersFrequency: Int {
        return String(self.filter { "0"..."9" ~= $0 }).count
    }
}

Usage

print("1, 2, and 3".numbersFrequency) // 3
print("tHis4is5test8,#pass11".numbersFrequency) //5

let newPassword = "tHis4is5test8,#pass11"
print(newPassword.numbersFrequency) //5

Upvotes: 3

Rakesha Shastri
Rakesha Shastri

Reputation: 11242

Here is an easier way. Change this line,

let stringArray = password.components(separatedBy: CharacterSet.decimalDigits.inverted)

to,

let stringArray = password.components(separatedBy: CharacterSet.decimalDigits)

Now the number of digits is one less than the number of elements in stringArray. So you could just use that.

if (stringArray.count - 1) > 4 {
    print("You Shall Pass!!")
} else {
     print("You Shall Not Pass!!")
}

Upvotes: 5

Related Questions