我需要检查单词是否以元音或辅音开头,如下:
let word = "ciao"
if wordStartsWithVowel {
print("Word starts with Vowel!")
}
我该怎么做?
答案 0 :(得分:1)
extension Character {
var isVowel: Bool { return ["a","e","i","o","u","A","E","I","O","U"].contains(self) }
var isConsonant: Bool { return ["b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z",
"B","C","D","F","G","H","J","K","L","M","N","P","Q","R","S","T","V","W","X","Y","Z"].contains(self) }
}
extension String {
var startsWithVowel: Bool {
return characters.first?.isVowel ?? false
}
var startsWithConsonant: Bool {
return characters.first?.isConsonant ?? false
}
}
let word = "ciao"
print(word.startsWithVowel) // false
print(word.startsWithConsonant) // true
或者如果您更喜欢使用NSCharacterSet:
extension Character {
struct CharacterSet {
static let vowel = NSCharacterSet(charactersInString: "aeiouAEIOU")
static let consonant = NSCharacterSet(charactersInString: "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ")
}
var characterSetValue: NSCharacterSet { return NSCharacterSet(charactersInString: String(self)) }
var isVowel: Bool { return CharacterSet.vowel.isSupersetOfSet(characterSetValue) }
var isConsonant: Bool { return CharacterSet.consonant.isSupersetOfSet(characterSetValue) }
}
"a".characters.first!.isConsonant // false
"a".characters.first!.isVowel // true
答案 1 :(得分:0)
let vowels: [Character] = ["a","e","i","o","u"]
let word = "ciao"
if vowels.contains(word.lowercased().characters.first!) {
print("Word starts with Vowel!")
}
.lowercaseString
很重要,否则,大写元音不会被识别为元音。