统计字符类型

前端之家收集整理的这篇文章主要介绍了统计字符类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用Swift语言实现,非常简单,具体代码如下:

func countChars(string: String) -> (vowels: Int,consonants: Int,others: Int) {
    var vowels = 0,consonants = 0,others = 0
    for character in string {
        var char = String(character).lowercaseString
        switch char {
        case "a","e","i","o","u":
            vowels++
        case "b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z":
            consonants++
        default:
            others++
        }
    }
    
    return (vowels,consonants,others)
}
let charsInfo = countChars("some arbitrary string!")
println("Vowels:\(charsInfo.vowels),Consonants:\(charsInfo.consonants),Othes:\(charsInfo.others)")


另外:

代码不是我写的,是官方的例子。我做了一点微小的改动而已。

猜你在找的Swift相关文章