Transliterate/transpose the characters in the NSString

前端 未结 3 827
不思量自难忘°
不思量自难忘° 2021-02-02 17:59

I want to transliterate a cyrillic string to it\'s closest latin equivalent. E.g. \"матрешка\" => \"matreshka\", \"водка\" => \"vodka\". So ideally I want some ready to use meth

相关标签:
3条回答
  • 2021-02-02 18:32

    Either try CFStringTransform function of CFMutableString with kCFStringTransformToLatin transform identifier or make a NSString category with simple mapping.

    Edited by the question poster: more specifically it should be:

    NSMutableString *buffer = [@"русский язык" mutableCopy];
    CFMutableStringRef bufferRef = (__bridge CFMutableStringRef)buffer;
    CFStringTransform(bufferRef, NULL, kCFStringTransformToLatin, false);
    NSLog(@"%@", buffer); // outputs "russkij âzyk"
    
    0 讨论(0)
  • 2021-02-02 18:44

    If you don't need diacritics or accents you can call CFStringTransform(bufferRef, NULL, kCFStringTransformStripCombiningMarks, false);

    Additional article: http://nshipster.com/cfstringtransform/

    0 讨论(0)
  • 2021-02-02 18:53

    With Swift 5, String has a method called applyingTransform(_:reverse:). applyingTransform(_:reverse:) has the following declaration:

    func applyingTransform(_ transform: StringTransform, reverse: Bool) -> String?
    

    The following Playground code shows how to use applyingTransform(_:reverse:) in order to transliterate from cyrillic to latin characters:

    import Foundation
    
    let string = "матрешка"
    let latinString = string.applyingTransform(StringTransform.toLatin, reverse: false)
    let noDiacriticString = latinString?.applyingTransform(StringTransform.stripDiacritics, reverse: false)
    
    print(latinString) // prints: Optional("matreška")
    print(noDiacriticString) // prints: Optional("matreska")
    

    As an alternative, you can use Core Foundation CFStringTransform(_:_:_:_:) function:

    import Foundation
    
    let mutableString = NSMutableString(string: "матрешка")
    
    CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
    print(mutableString) // prints: matreška
    
    CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
    print(mutableString) // prints: matreska
    
    0 讨论(0)
提交回复
热议问题