將字元的出現次數計入字串
鑑於 String
和 Character
let text = "Hello World"
let char: Character = "o"
我們可以計算 Character
出現在 String
中的次數
let sensitiveCount = text.characters.filter { $0 == char }.count // case-sensitive
let insensitiveCount = text.lowercaseString.characters.filter { $0 == Character(String(char).lowercaseString) } // case-insensitive