Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transliterate/transpose the characters in the NSString

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 method on the NSString or somewhere else that already knows everything about the alphabets and can do the conversation.

But if such functionality doesn't exist in the iOS APIs then I will be totally happy with something like ruby's tr method that just replaces the characters in a string using a simple mapping specified as a parameter.

"баба".tr('абвгд', 'abvgd')
like image 873
Dmitry Sokurenko Avatar asked Apr 19 '12 12:04

Dmitry Sokurenko


2 Answers

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"
like image 116
ksh Avatar answered Oct 17 '22 05:10

ksh


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

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

like image 44
ksoftware Avatar answered Oct 17 '22 04:10

ksoftware