Swift 2 : Iterating and upper/lower case some characters

霸气de小男生 提交于 2019-12-01 05:09:50

String has a upperCaseString method, but Character doesn't. The reason is that in exotic languages like German, converting a single character to upper case can result in multiple characters:

print("ß".uppercaseString) // "SS"

The toupper/tolower functions are not Unicode-safe and not available in Swift.

So you can enumerate the string characters, convert each character to a string, convert that to upper/lowercase, and concatenate the results:

func lowercaseDestination(str : String) -> String {
    var result = ""
    for c in str.characters {
        let s = String(c)
        if condition {
            result += s.lowercaseString
        } else {
            result += s.uppercaseString
        }
    }
    return result
}

which can be written more compactly as

func lowercaseDestination(str : String) -> String {
    return "".join(str.characters.map { c -> String in
        let s = String(c)
        return condition ? s.lowercaseString : s.uppercaseString
    })
}

Re your comment: If the condition needs to check more than one character then you might want to create an array of all characters first:

func lowercaseDestination(str : String) -> String {

    var result = ""
    let characters = Array(str.characters)
    for i in 0 ..< characters.count {
        let s = String(characters[i])
        if condition {
            result += s.lowercaseString
        } else {
            result += s.uppercaseString
        }
    }
    return result
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!