Check if a word starts with a Vowel or a Consonant

人走茶凉 提交于 2019-12-13 07:47:24

问题


I need to check if a word starts with a vowel or a consonant, something like that:

let word = "ciao"

if wordStartsWithVowel {
    print("Word starts with Vowel!")
}

How can I do that?


回答1:


extension Character {
    var isVowel: Bool {
        return "aeiouAEIOU".contains {
            String($0).compare(String(self).folding(options: .diacriticInsensitive, locale: nil), options: .caseInsensitive) == .orderedSame
        }
    }
}

extension StringProtocol {
    var startsWithVowel: Bool {
        return first?.isVowel == true
    }
}

let word = "ciao"

print(word.startsWithVowel)      // false

let word2 = "é"
print(word2.startsWithVowel)    // true 



回答2:


let vowels: [Character] = ["a","e","i","o","u"]
let word = "ciao"

if vowels.contains(word.lowercased().characters.first!) {
    print("Word starts with Vowel!")
}

.lowercaseString is important because, otherwise, uppercase vowels wouldn't be recognised as vowels.



来源:https://stackoverflow.com/questions/35493089/check-if-a-word-starts-with-a-vowel-or-a-consonant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!