swift2 辅音和元音Swift

kwvwclae  于 2022-11-06  发布在  Swift
关注(0)|答案(3)|浏览(155)

我是Swift的新手,谁能解释一下为什么我总是遇到这个问题。我使用的是Xcode 6.4,但我的问题是,我希望我能解决它,但我需要我的函数接受大字符串,然后返回元组(numVowels,numConsonants)计算以辅音/元音开头的单词的个数返回元组并打印函数调用的结果。我不需要它来计算字符数,我创建了一个for循环,它会将所有字符都转换为小写。但是现在我被卡住了。

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)
}
fslejnso

fslejnso1#

如果您使用的是swift 2:
就改这一行

for character in string {

for character in string.characters {

而且它会工作得很好

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

wyyhbhjk2#

这里的问题是你为你的方法选择的名字。尝试count以外的任何名字,你应该没问题。
编辑/更新:雨燕4
第一个
如果您只想计算每个单词的第一个字母,则需要将字符串分解为单词数组,并提取每个第一个字母的小写字母,如下所示:
第一个
请注意,扩展名应放置在项目内的新Swift文件中。

brtdzjyr

brtdzjyr3#

另一个选项是使用正则表达式来检索每个单词的第一个字母。\b选项用于查找单词边界,而\w是一个单词字符。因此,一旦您转义反斜杠,\\b\\w将捕获紧跟在单词边界后面的第一个字母(也就是每个单词的第一个字母):

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)
}

--
如果您想要处理重音字符(例如“étude”),您可能需要先移除这些音调符号:

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)
}

相关问题