gpt4 book ai didi

comparison - Swift 中如何判断字母是字母数字还是数字

转载 作者:行者123 更新时间:2023-11-30 11:24:24 26 4
gpt4 key购买 nike

我想计算以下字符串中字母、数字和特殊字符的数量:

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

我尝试过:

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

但我收到错误。我尝试了各种其他变体 - 仍然出现错误 - 例如:

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

最佳答案

对于 Swift 5,请参阅 rustylepord's answer .

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 开始,第一个解决方案不再有效,因为isAlpha() 和相关的(仅限 ASCII)方法已从 Swift 中删除。第二种解决方案仍然有效。

关于comparison - Swift 中如何判断字母是字母数字还是数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50922227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com