統計字符類型

使用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)")


另外:

這代碼不是我寫的,是官方的例子。我做了一點微小的改動而已。

發佈了87 篇原創文章 · 獲贊 9 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章