Consonants and Vowels Swift

流过昼夜 提交于 2019-12-04 02:42:43

问题


I'm new at Swift, could anyone explain to me why I'm keep getting this problem. I'm using Xcode 6.4, but here is my question I hope I cleared it up but I needed my Function to takes in Large String then returns Tuple(numVowels, numConsonants) Count the number of words that start with consonants/vowels Return the Tuple and print the result of the function call. I did not need for it to count characters, only first character of each word. I create an for loop which will switch everything to lowercase. But now I'm stuck.

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

    }
    return (Vowels, Consonants)
}

回答1:


if you are using swift 2 :

just change this line

for character in string {

to

for character in string.characters {

and it would work just fine

count("hello") // (.0 2, .1 3)



回答2:


Another option is to use regular expression to retrieve the first letter of every word. The \b option is used to find word boundaries, and \w is a single word character. Thus, once you escape the back slashes, \\b\\w will capture the first letter immediately following a word boundary (a.k.a., the first letter of every word):

func countLetters(string: String) -> (vowels: Int, consonants: Int) {
    var vowels = 0, consonants = 0
    let regex = NSRegularExpression(pattern: "\\b\\w", options: nil, error: nil)
    regex?.enumerateMatchesInString(string, options: nil, range: NSMakeRange(0, count(string))) { matches, flags, stop in
        switch (string as NSString).substringWithRange(matches.range).lowercaseString {
        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: break
        }
    }
    return (vowels, consonants)
}

--

If you want to handle accented characters (e.g. "étude"), you might want to remove those diacritics first:

func countLetters(string: String) -> (vowels: Int, consonants: Int) {
    let convertedString = NSMutableString(string: string)
    CFStringTransform(convertedString, nil, kCFStringTransformStripCombiningMarks, Boolean(0))

    var vowels = 0, consonants = 0
    let regex = NSRegularExpression(pattern: "\\b\\w", options: nil, error: nil)
    regex?.enumerateMatchesInString(convertedString as String, options: nil, range: NSMakeRange(0, convertedString.length)) { matches, flags, stop in
        switch convertedString.substringWithRange(matches.range).lowercaseString {
        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: break
        }
    }
    return (vowels, consonants)
}



回答3:


The problem there is the name that you choose for your method. Try any name other than count and you should be fine.

edit/update: Swift 4

func countCharacteres(_ string: String) -> (vowels: Int, consonants: Int) {
    var vowels = 0, consonants = 0
    for character in string {
        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)
}

let name = "Dromel"
countCharacteres(name).vowels      // 2
countCharacteres(name).consonants  // 4

If you want to count only the first letter of each word you need to break your string into an array of words and extract the lowercase of each first letter as follow:

extension StringProtocol where Index == String.Index {
    var range: Range<Index> { return startIndex..<endIndex }
    var words: [String] {
        var words: [String] = []
        enumerateSubstrings(in: range, options: .byWords) { word, _, _, _ in words.append(word!) }
        return words
    }
}
extension StringProtocol  where Index == String.Index {
    var firstCharacterCount: (vowels: Int, consonants: Int) {
        var vowels = 0, consonants = 0
        for first in words.compactMap({$0.lowercased().first}) {
            switch first {
            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)
    }
}

let sentence = "Hello World. Apple."
let counter =  sentence.firstCharacterCount
counter.vowels      // 1
counter.consonants  // 2

Note that the extension should be placed in a new Swift file inside your project.



来源:https://stackoverflow.com/questions/31954013/consonants-and-vowels-swift

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