Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

comparison - How to find out if letter is Alphanumeric or Digit in Swift

I want to count the number of letters, digits and special characters in the following string:

let phrase = "The final score was 32-31!"

I tried:

for tempChar in phrase {
    if (tempChar >= "a" && tempChar <= "z") {
       letterCounter++
    }
// etc.

but I'm getting errors. I tried all sorts of other variations on this - still getting error - such as:

could not find an overload for '<=' that accepts the supplied arguments

question from:https://stackoverflow.com/questions/24502669/how-to-find-out-if-letter-is-alphanumeric-or-digit-in-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For Swift 5 see rustylepord's answer.

Update for Swift 3:

let letters = CharacterSet.letters
let digits = CharacterSet.decimalDigits

var letterCount = 0
var digitCount = 0

for uni in phrase.unicodeScalars {
    if letters.contains(uni) {
        letterCount += 1
    } else if digits.contains(uni) {
        digitCount += 1
    }
}

(Previous answer for older Swift versions)

A possible Swift solution:

var letterCounter = 0
var digitCount = 0
let phrase = "The final score was 32-31!"
for tempChar in phrase.unicodeScalars {
    if tempChar.isAlpha() {
        letterCounter++
    } else if tempChar.isDigit() {
        digitCount++
    }
}

Update: The above solution works only with characters in the ASCII character set, i.e. it does not recognize ?, é or ? as letters. The following alternative solution uses NSCharacterSet from the Foundation framework, which can test characters based on their Unicode character classes:

let letters = NSCharacterSet.letterCharacterSet()
let digits = NSCharacterSet.decimalDigitCharacterSet()

var letterCount = 0
var digitCount = 0

for uni in phrase.unicodeScalars {
    if letters.longCharacterIsMember(uni.value) {
        letterCount++
    } else if digits.longCharacterIsMember(uni.value) {
        digitCount++
    }
}

Update 2: As of Xcode 6 beta 4, the first solution does not work anymore, because the isAlpha() and related (ASCII-only) methods have been removed from Swift. The second solution still works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...