Monday, December 13, 2010

Your Japanese Name for iOS, part 18

The app will have two ways to convert latin characters into katakana characters. First one is a dictionary that I wrote with Nachi for Your Japanese Name on Facebook. If a name isn't in the dictionary, then the second way is an algorithm. Actually the algorithm is almost as good as the dictionary is, because the conversion is quite straightforward.

I wrote the algo originally in Python, where it was 6k in size. I just finished the Objective-C conversion and it turned out to be 8.5k. Luckily Cocoa had good unicode support, so it wasn't nearly as bad as I feared. Doing things like removing diacritics was as easy on both. Line with the difference was biggest was
r = s[::-1].replace("l", "r") 

Which in Obj-C became

+ (NSString *)stringReversedFromString:(NSString *)s {
NSMutableString *reversed = [NSMutableString stringWithString:@""];
NSUInteger len = [s length];
for (int i = len - 1; i >= 0; i--) {
unichar ch = [s characterAtIndex:i];
NSString *charStr = [NSString stringWithFormat:@"%C", ch];
[reversed appendString:charStr];
return reversed;


NSMutableString *r = [[self stringReversedFromString:s] mutableCopy];
NSRange replaceRange = NSMakeRange(0, [r length]);
[r replaceOccurrencesOfString:@"l" withString:@"r" options:NSCaseInsensitiveSearch range:replaceRange];