创建一个函数来计算句子中的元音,辅音和标点

时间:2018-10-29 15:42:25

标签: swift function punctuation

我一直在到处寻找问题的好答案。如何创建一个函数来计算句子中的元音,辅音和标点字符。我设法找到了前两个答案,而不是最后一个。

func findVowelsConsonantsPunctuation(_ sentence:String) -> (Vowels:Int, Consonants:Int, Punctuation:Int) {
    var Vowels = 0, Consonants = 0, Punctuation = 0
    for character in sentence {
        switch String(character).lowercased() {
        case "a","e","i","o","u":
            Vowels += 1
        case "b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z":
            Consonants += 1
        default:
            break
        }
    }

    return (Vowels, Consonants, Punctuation)
}

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

extension CharacterSet {
    static let vowels: CharacterSet = CharacterSet(charactersIn: "aeiou")
    static let consonants = CharacterSet.letters.subtracting(.vowels)
}

func findVowelsConsonantsPunctuation(_ sentence: String) -> (vowels: Int, consonants: Int, punctuation: Int) {
    //Let's ignore diacritics
    let str = sentence.folding(options: .diacriticInsensitive, locale: .current)

    //The counters
    var vowels = 0, consonants = 0, punctuation = 0

    for character in str {
        let charSet = CharacterSet(charactersIn: String(character))

        //Consonants
        if CharacterSet.consonants.isSuperset(of: charSet) {
            consonants += 1
        }

        //Vowels
        else if CharacterSet.vowels.isSuperset(of: charSet) {
            vowels += 1
        }

        //Anything other than letters is considered as punctuation
        else {
            punctuation += 1
        }
    }

    return (vowels, consonants, punctuation)
}

以下是一些示例:

findVowelsConsonantsPunctuation("Hellö world! ")  //(vowels 3, consonants 7, punctuation 4)
findVowelsConsonantsPunctuation("H311o")            //(vowels 1, consonants 1, punctuation 3)

一种编写上述功能的Swift方法是:

func findVowelsConsonantsPunctuation(_ sentence: String) -> (consonants: Int, vowels: Int, punctuation: Int) {
    let str = sentence.folding(options: .diacriticInsensitive, locale: .current)
    return str.reduce((0, 0, 0)) { tuple, character in
        let charSet = CharacterSet(charactersIn: String(character))
        if CharacterSet.consonants.isSuperset(of: charSet) {
            return (tuple.0 + 1, tuple.1, tuple.2)
        }
        else if CharacterSet.vowels.isSuperset(of: charSet) {
            return (tuple.0, tuple.1 + 1, tuple.2)
        }
        else {
            return (tuple.0, tuple.1, tuple.2 + 1)
        }
    }
}

我已将元音和辅音的顺序更改为返回值,因为找到辅音的可能性比元音高,这意味着如果第一个条件满足的话,第一个条件会比其他条件更常见。