Swift 练笔 —— 统计元音字母
2017-01-16 本文已影响18人
码上说
/***********************************************************
@Execise:
统计元音字母:
计算一段字符串中元音字母出现的频次
@notice:
1. 网上有看到各种实现方式,有用元组记录的,但个人觉得字典最简洁
***********************************************************/
// 元音字母集合
let vowels: Set<Character> = ["A", "E", "I", "O", "U"]
// 获取元音字母出现的频次
func getVowelNum(_ string: String) -> [String:Int] {
var dict: [String:Int] = ["A":0, "E":0, "I":0, "O":0, "U":0]
for c in string.characters {
let s = String(c).uppercased()
if dict[s] != nil {
dict[s]! += 1
}
}
return dict
}
// 测试
print(getVowelNum("The goals of an NPO are always to change or improve a social issue."))
print(getVowelNum("IEEE stands for the 'Institute of Electrical and Electronics Engineers'."))
// 输出
// ["O": 7, "A": 8, "I": 3, "U": 1, "E": 5]
// ["O": 3, "A": 3, "I": 6, "U": 1, "E": 12]