/** 判断字符出现的次数 */
let str = "asfkj294sjdkflskadjw8tghjhf8t8as"
//定义一个字典统计个字符的出现次数
var status : [Character : Int] = [:]
for ch in str
{
//获取ch字符出现的次数
var num = status[ch]
//如果一次未出现,会返回nil
if num != nil
{
status[ch] = num! + 1
}
else
{
status[ch] = 1
}
}
//[j: 4,w: 1,f: 3,9: 1,k: 3,d: 2,t: 2,2: 1,a: 3,8: 3,4: 1,s: 4,l: 1,g: 1,h: 2]
println(status)
//遍历status的value集合,找出最大的出现次数
var maxOccurs = 0
for occurs in Array(status.values)
{
if occurs > maxOccurs
{
maxOccurs = occurs
}
}
//找出最后出现次数最多的对应字符
for (ch,occurs) in status
{
if occurs == maxOccurs
{
//出现最多的字符 j,出现的次数4
//出现最多的字符 s,出现的次数4
println("出现最多的字符 \(ch),出现的次数\(occurs)")
}
}