Swift 2 : Iterating and upper/lower case some characters

妖精的绣舞 提交于 2019-12-01 02:47:54

问题


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

In Obj-c I had following :

- (NSString*) lowercaseDestination:(NSString*) string {
    NSUInteger length = string.length;
    unichar buf[length+1];
    [string getCharacters:buf];

    BOOL up = true;
    for (int i=0; i< length ; i++) {
        unichar chr = buf[i];

        if( .... ) {
            buf[i] = toupper(chr);
        } else {
            buf[i] = tolower(chr);
        }
    }
    string = [NSString stringWithCharacters:buf length:length];
    return string;

How would you do that in Swift 2 ?

I did no find any Character method to upper or lower the case.

Would be an array of String of 1 character be an option ? (And then use String methods to upper and lower each String


回答1:


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
}


来源:https://stackoverflow.com/questions/31871395/swift-2-iterating-and-upper-lower-case-some-characters

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