Swift,stringByReplacingOccurencesOfString和replace数组

时间:2014-10-16 14:45:11

标签: php arrays dictionary replace swift

我需要替换数字字符。我的意思是我想用字符串中的bengali聊天替换english char。比方说,我有两个数组,

var enDigits = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]var bnDigits = ["১", "২", "৩", "৪", "৫", "৬", "৭", "৮", "৯", "০"]

我在iOS&绝对是快速的。在PHP中,str_replace()可以轻松完成。但是,我搜索并发现stringByReplacingOccurencesOfString代表swift,但无法弄清楚是否可以使用数组。我需要你的建议。

2 个答案:

答案 0 :(得分:4)

这是一个非常具体的答案,但如果您只是想要替换角色的字符,可以在源字符串上使用map函数,如下所示:

let enDigits: [Character] = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
let bnDigits: [Character] = ["১", "২", "৩", "৪", "৫", "৬", "৭", "৮", "৯", "০"]

let enString = "Jenny's number is 867-5309"
let bnString = String(map(enString, { ch in
    if let index = find(enDigits, ch) {
        return bnDigits[index]
    }
    return ch
}))
// Jenny's number is ৮৬৭-৫৩০৯

答案 1 :(得分:2)

如果您真的希望转换为孟加拉语数字,Cocoa提供了执行ICU transforms的API:

var string = "Jenny's number is 867-5309"
let transform = "[:Number:]; Any-Latin; Latin-Bengali"

let cfstr = NSMutableString(string: String(string)) as CFMutableString
var range = CFRangeMake(0, CFStringGetLength(cfstr))
CFStringTransform(cfstr, &range, ((transform as NSString) as CFString), 0)

println(cfstr) // Jenny's number is ৮৬৭-৫৩০৯