Fast string replacement

I want to replace some characters with English letters using Swift. Replace code:

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)
}

      

It does not replace "ğ" with "g". Which is weird if I print it right out like this:

result = city.stringByReplacingOccurrencesOfString("ğ", withString: "g", options: NSStringCompareOptions.CaseInsensitiveSearch | NSStringCompareOptions.LiteralSearch, range: nil)

      

it works great.

Why isn't this the case when I first assign the value to a variable String

?

+4


source to share


2 answers


It looks like you are trying to remove various accents and diacritics. One way to do this is to use CFStringTransform

.

In Swift, it will look something like this:

let original = "šÜįéïöç"
var mutableString = NSMutableString(string: original) as CFMutableStringRef
CFStringTransform(mutableString, nil, kCFStringTransformStripCombiningMarks, Boolean(0))

let normalized = (mutableString as NSMutableString).copy() as! NSString
// = sUieioc

      



Edit

As pointed out by Martin R. in the comments . You can do the same without Core Foundation:

let original = "šÜįéïöç"
let normalized = original.stringByFoldingWithOptions(.DiacriticInsensitiveSearch, locale: NSLocale.currentLocale())
// = sUieioc

      

+11


source


This is because you are replacing the appearance of the city, but you are assigning a new value. Thus, only the last character is replaced in the result. Just remove the result variable and change this line:

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)

      

+2


source







All Articles