问题描述
我要计算以下字符串中的字母,数字和特殊字符的数量:
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:
推荐答案
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版本的答案)
可能的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 alternativesolution uses NSCharacterSet
from the Foundation framework, which can test charactersbased 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, becausethe isAlpha()
and related (ASCII-only) methods have been removed from Swift.The second solution still works.
这篇关于如何在Swift中找出字母是字母数字还是数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!