如何使用CFStringTransform正确音译西里尔文,没有变音符号?

时间:2013-05-14 12:14:43

标签: ios objective-c nsstring cyrillic

我正在尝试使用CFStringTransform将以俄语输入的名称音译为安全的ASCII信用卡处理。然而,当剥离变音符号č变成c时,这实际上不是一个好的音译。无论如何我可以使用CFStringTransform,没有变音符号吗?换句话说,ч应该返回ch,因为几乎每个标准都应该返回http://en.wikipedia.org/wiki/Romanization_of_Russian

NSMutableString *name = [@"романчук" mutableCopy];
CFMutableStringRef nameRef = (__bridge CFMutableStringRef)name;
CFStringTransform(nameRef, NULL, kCFStringTransformToLatin, false); //name is romančuk
CFStringTransform(nameRef, NULL, kCFStringTransformStripCombiningMarks, false); //name is now romancuk

1 个答案:

答案 0 :(得分:7)

为NSString创建类别并添加以下方法:

- (NSString *)toLatinWithDictionary
{
    NSMutableString *newString = [NSMutableString string];
    NSRange range;
    NSString *symbol;
    NSString *newSymbol;

    for (NSUInteger i = 0; i < [self length]; i ++)
    {
         //  Take regular symbol
        range = NSMakeRange(i, 1);
        symbol = [self substringWithRange:range];
        newSymbol = [self transliterateChar:symbol];
        if (newSymbol != nil)
        {
            [newString appendString:newSymbol];
        }
        else
        {
            [newString appendString:symbol];
        }
    }
    return [NSString stringWithString:newString];
}

- (NSString *)transliterateChar:(NSString *)symbol
{
    //  For simlicity there is only
    NSArray *cyrillicChars = @[@"а", @"б", @"в", @"г", @"д", @"е", @"ё", @"ж", @"з", @"и", @"й", @"к", @"л", @"м", @"н", @"о", @"п", @"р", @"с", @"т", @"у", @"ф", @"х", @"ц", @"ч", @"ш", @"щ", @"ъ", @"ы", @"ь", @"э", @"ю", @"я"];
    NSArray *latinChars = @[@"a", @"b", @"v", @"g", @"d", @"e", @"yo", @"zh", @"z", @"i", @"y", @"k", @"l", @"m", @"n", @"o", @"p", @"r", @"s", @"t", @"u", @"f", @"h", @"ts", @"ch", @"sh", @"shch", @"'", @"y", @"'", @"e", @"yu", @"ya"];
    NSDictionary *convertDict = [NSDictionary dictionaryWithObjects:latinChars
                                                            forKeys:cyrillicChars];
    return [convertDict valueForKey:[symbol lowercaseString]];
}