我想使用Swift用英文字母替换一些字符。替换代码:
let turkish = ["ı", "ğ", "ü", "ş", "ö", "ç"]
let english = ["i", "g", "u", "s", "o", "c"]
var city = "Ağri"
var result = ""
for i in 0..<turkish.count {
var target = turkish[i]
var destination = english[i]
result = city.stringByReplacingOccurrencesOfString(target, withString: destination, options: NSStringCompareOptions.CaseInsensitiveSearch | NSStringCompareOptions.LiteralSearch, range: nil)
}
它不会将“ğ”替换为“g”。奇怪的是,如果我直接输入它:
result = city.stringByReplacingOccurrencesOfString("ğ", withString: "g", options: NSStringCompareOptions.CaseInsensitiveSearch | NSStringCompareOptions.LiteralSearch, range: nil)
它完美无缺。
为什么不是,当我第一次将值赋给String
变量时?
答案 0 :(得分:11)
看起来你正试图删除各种口音和变音符号。您可以这样做的一种方法是使用CFStringTransform
。
在Swift中它看起来像这样:
let original = "šÜįéïöç"
var mutableString = NSMutableString(string: original) as CFMutableStringRef
CFStringTransform(mutableString, nil, kCFStringTransformStripCombiningMarks, Boolean(0))
let normalized = (mutableString as NSMutableString).copy() as! NSString
// = sUieioc
与pointed out by Martin R in the comments一样。没有Core Foundation,您也可以这样做:
let original = "šÜįéïöç"
let normalized = original.stringByFoldingWithOptions(.DiacriticInsensitiveSearch, locale: NSLocale.currentLocale())
// = sUieioc
答案 1 :(得分:2)
发生这种情况是因为您替换了城市的出现次数,但是将新值分配给结果。这样只会在结果中替换最后一个字符。 只需删除结果变量并更改此行:
result = city.stringByReplacingOccurrencesOfString(target, withString: destination, options: NSStringCompareOptions.CaseInsensitiveSearch | NSStringCompareOptions.LiteralSearch, range: nil)
到此:
city = city.stringByReplacingOccurrencesOfString(target, withString: destination, options: NSStringCompareOptions.CaseInsensitiveSearch | NSStringCompareOptions.LiteralSearch, range: nil)