Swift 2 : Iterating and upper/lower case some characters

前端 未结 1 625
-上瘾入骨i
-上瘾入骨i 2021-01-12 19:52

I want to modify a Swift string by converting some characters to uppercase, some others to lowercase.

In Obj-c I had following :

- (NSString*) lowe         


        
相关标签:
1条回答
  • 2021-01-12 20:34

    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
    }
    
    0 讨论(0)
提交回复
热议问题