輸入一個字符串,統計其中英文元音字母 (a,e,i,o,u)、輔音字母 (其餘字母) 及其他字符 (數字、符號、空格等) 的個數。不區分大小寫。
func countChars(string: String) -> (vowels: Int, consonants: Int, others: Int) {
var vowels = 0, consonants = 0, others = 0
for character in string {
let char = String(character).lowercased()
switch char {
case "a", "e", "i", "o", "u":
vowels += 1
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
consonants += 1
default:
others += 1
}
}
return (vowels, consonants, others)
}
// 使用示例
let charsInfo = countChars("some arbitrary string!")
print("Vowels: \(charsInfo.vowels), Consonants: \(charsInfo.consonants), Others: \(charsInfo.others)")
// 輸出: Vowels: 6, Consonants: 12, Others: 2
註:此代碼基於 Swift 官方示例修改,展示 Swift 字符串處理與元組返回特性。