Cocoa/Objective C: Convert numbers to strings using Japanese unicode characters
Converting numbers to strings is no problem, but the string created uses ascii numbers. I am inserting the number in a Japanese sentence. The character itself is correct, say 3, for example, but the width and positioning should be a little different when typing in Japanese. As a result the number looks cramped up against the following character. Is there any clever non-manual way to convert 1 to 1, 2 to 2开发者_开发问答, 3 to 3, etc.?
For lack of any better ideas, I wrote up a not-so-elegant category solution that manually converts each character. If anyone has a better solution, please let me know.
#import "NSNumber+LocalizedNumber.h"
@interface NSNumber()
-(NSString*)convertRepresentation:(unichar)character;
@end
@implementation NSNumber (LocalizedNumber)
-(NSString *)localizedNumber {
NSString *languageCode = [[NSLocale preferredLanguages] objectAtIndex:0];
if([languageCode isEqualToString:@"ja"]) {
NSString *numberString = [self stringValue];
NSUInteger length = [numberString length];
NSMutableString *convertedString = [[NSMutableString alloc] initWithCapacity:length];
for(NSUInteger index = 0; index < length; index++) {
unichar character = [numberString characterAtIndex:index];
[convertedString appendString:[self convertRepresentation:character]];
}
return [convertedString autorelease];
}
return [self stringValue];
}
-(NSString*)convertRepresentation:(unichar)character {
switch (character) {
case '1':
return @"1";
case '2':
return @"2";
case '3':
return @"3";
case '4':
return @"4";
case '5':
return @"5";
case '6':
return @"6";
case '7':
return @"7";
case '8':
return @"8";
case '9':
return @"9";
case '0':
return @"0";
default:
return nil;
}
}
精彩评论