swift remove diacritic from Arabic

蓝咒 提交于 2019-12-08 00:08:41

问题


I am trying to remove the Arabic text diacritic. For example I need to convert this َب to this ب , here is my code :

if (text != "") {
    for char in text! {
        print(char)
        print(char.unicodeScalars.first?.value)
        if allowed.contains("\(char)"){
            newText.append(char)
        }
    }
    self.textView.text = text!
} else {
//            TODO :
//            show an alert
    print("uhhh no way")
}

I have tried these solutions but with no luck :

How to remove diacritics from a String in Swift?

NSString : easy way to remove UTF-8 accents from a string?


回答1:


You can use Regex, try this code

 let myString = "الْحَمْدُ لِلَّهِ رَبِّ الْعَالَمِينَ"
        let regex = try! NSRegularExpression(pattern: "[\\u064b-\\u064f\\u0650-\\u0652]", options: NSRegularExpression.Options.caseInsensitive)
        let range = NSMakeRange(0, myString.unicodeScalars.count)
        let modString = regex.stringByReplacingMatches(in: myString, options: [], range: range, withTemplate: "")
        print(modString)

Output : الحمد لله رب العالمين




回答2:


you can use CFStringTransform with kCFStringTransformStripCombiningMarks

to remove (accents or diacritics)

        let original = "ََب"
        let mutableString = NSMutableString(string: original) as CFMutableString
        CFStringTransform(mutableString, nil, kCFStringTransformStripCombiningMarks, Bool(truncating: 0))
        let normalized = (mutableString as NSMutableString).copy() as! NSString

        print(normalized)

CFStringTransform

A constant containing the transformation of a string by removing combining marks.

kCFStringTransformStripCombiningMarks

The identifier of a transform to strip combining marks (accents or diacritics).




回答3:


Use this extension:

extension String {
    /// strip combining marks (accents or diacritics)
    var stripDiacritics: String {
        let mStringRef = NSMutableString(string: self) as CFMutableString
        CFStringTransform(mStringRef, nil, kCFStringTransformStripCombiningMarks, false)
        return mStringRef as String
    }
}



来源:https://stackoverflow.com/questions/50679443/swift-remove-diacritic-from-arabic

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