Swift 2:迭代和大写/小写一些字符 [英] Swift 2 : Iterating and upper/lower case some characters

查看:115
本文介绍了Swift 2:迭代和大写/小写一些字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过将某些字符转换为大写字母,另一些字符转换为小写字母来修改Swift字符串.

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

在Obj-c中,我有以下内容:

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;

您将如何在Swift 2中做到这一点?

How would you do that in Swift 2 ?

我找不到大写或小写的任何Character方法.

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

是否可以选择由1个字符组成的String数组? (然后使用String方法上下移动每个String

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

推荐答案

String具有upperCaseString方法,但Character没有. 原因是在外来语言(如德语)中, 字符转换为大写字母可能会导致多个字符:

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"

toupper/tolower函数不是Unicode安全的,并且不是 在Swift中可用.

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
}

可以更紧凑地写为

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


发表评论:如果条件需要检查多个 字符,那么您可能想创建所有字符的 array 首先:


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
}

这篇关于Swift 2:迭代和大写/小写一些字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆