我想计算以下字符串中的字母,数字和特殊字符数:
let phrase = "The final score was 32-31!"
我试过了:
for tempChar in phrase {
if (tempChar >= "a" && tempChar <= "z") {
letterCounter++
}
// etc.
但我收到了错误。我尝试了各种其他变体 - 仍然出现错误 - 例如:
找不到接受提供的参数
的'&lt; ='的重载
答案 0 :(得分:52)
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解决方案:
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字符类:
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开始,第一个解决方案不再有效,因为
已从Swift中删除isAlpha()
和相关(仅限ASCII)方法。
第二种解决方案仍然有效。
答案 1 :(得分:4)
使用unicodeScalars的值
let phrase = "The final score was 32-31!"
var letterCounter = 0, digitCounter = 0
for scalar in phrase.unicodeScalars {
let value = scalar.value
if (value >= 65 && value <= 90) || (value >= 97 && value <= 122) {++letterCounter}
if (value >= 48 && value <= 57) {++digitCounter}
}
println(letterCounter)
println(digitCounter)
答案 2 :(得分:0)
我为String
extension String {
var letterCount : Int {
return self.unicodeScalars.filter({ CharacterSet.letters.contains($0) }).count
}
var digitCount : Int {
return self.unicodeScalars.filter({ CharacterSet.decimalDigits.contains($0) }).count
}
}
或用于计算您输入的任何CharacterSet
的计数的函数
extension String {
func characterCount(for set: CharacterSet) -> Int {
return self.unicodeScalars.filter({ set.contains($0) }).count
}
}
用法:
let phrase = "the final score is 23-13!"
let letterCount = phrase.characterCount(for: .letters)
答案 3 :(得分:0)
对于Swift 5,您可以对简单的字符串执行以下操作,但请谨慎处理“1️⃣”,“④”等字符,这些字符也将被视为数字。
let phrase = "The final score was 32-31!"
var numberOfDigits = 0;
var numberOfLetters = 0;
var numberOfSymbols = 0;
phrase.forEach {
if ($0.isNumber) {
numberOfDigits += 1;
}
else if ($0.isLetter) {
numberOfLetters += 1
}
else if ($0.isSymbol || $0.isPunctuation || $0.isCurrencySymbol || $0.isMathSymbol) {
numberOfSymbols += 1;
}
}
print(#"\#(numberOfDigits) || \#(numberOfLetters) || \#(numberOfSymbols)"#);
答案 4 :(得分:0)
如果您只需要一个信息(字母或数字或符号),您可以在一行中完成:
let phrase = "The final score was 32-31!"
let count = phrase.filter{ $0.isLetter }.count
print(count) // "16\n"
但是多次执行 phrase.filter
效率低下,因为它会遍历整个字符串。