Swift:如何找出字母是字母数字还是数字 [英] Swift: how to find out if letter is Alphanumeric or Digit
问题描述
我想计算以下字符串中的字母,数字和特殊字符数:
I want to count the number of letters, digits and special characters in the following string:
let phrase = "The final score was 32-31!"
我试过:
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
任何线索?
推荐答案
一个可能的Swift解决方案:
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++
}
}
上述解决方案仅适用于ASCII字符集中的字符
,即它不能将Ä,é或ø识别为字母。以下备选
解决方案使用Foundation框架中的 NSCharacterSet
,它可以根据其Unicode字符类测试字符
:
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++
}
}
更新2:自Xcode 6 beta 4起,第一个解决方案不再工作,因为
isAlpha ()
和相关(仅限ASCII)方法已从Swift中删除。
第二个解决方案仍然有效。
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.
Swift 3更新 p>
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
}
}
这篇关于Swift:如何找出字母是字母数字还是数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!