swift给定一个字符串,统计字符串中大小写字母、数字、空格及其他未识别类型字符个数
时间: 2024-10-13 13:06:43 浏览: 24
Swift算法实现字符串转数字的方法示例
在Swift中,你可以使用`Scanner`或`Collections`框架来统计一个字符串中各个类型的字符数。这里是一个简单的示例:
```swift
import Foundation
func countCharactersInString(_ input: String) -> [CharacterCount: Int] {
var characterCounts = ["lowercase": 0, "uppercase": 0, "digits": 0, "spaces": 0, "other": 0]
let scanner = Scanner(string: input)
while scanner.scanCharacters(from: .alphanumerics) {
if Character.isLowercase(scanner.scanLocation == 0) {
characterCounts["lowercase"] += 1
} else if Character.isUppercase(scanner.scanLocation == 0) {
characterCounts["uppercase"] += 1
} else if scanner.string[scanner.location - 1].isNumber {
characterCounts["digits"] += 1
} else if scanner.string[scanner.location - 1] == " " {
characterCounts["spaces"] += 1
} else {
characterCounts["other"] += 1
}
scanner.scanLocation++
}
return characterCounts
}
let inputString = "Hello World! 123"
let result = countCharactersInString(inputString)
print("Character counts:")
for (category, count) in result {
print("\(category): \(count)")
}
阅读全文