How to convert english numbers inside a string to Persian/Arabic numbers in Objective-C?

前端 未结 10 1984
轮回少年
轮回少年 2021-01-18 10:53

I have an english string that may or may not have numbers. But i want those numbers to be printed on screen as Persian numbers.

For example if NSString *foo =

10条回答
  •  伪装坚强ぢ
    2021-01-18 11:31

    The simple way:

    NSDictionary *numbersDictionary = @{@"1" : @"۱", @"2" : @"۲", @"3" : @"۳", @"4" : @"۴", @"5" : @"۵", @"6" : @"۶", @"7" : @"۷", @"8" : @"۸", @"9" : @"۹"};
    for (NSString *key in numbersDictionary) {
      str = [str stringByReplacingOccurrencesOfString:key withString:numbersDictionary[key]];
    }
    

    Other solution more flexible with locale:

    NSNumberFormatter *formatter = [NSNumberFormatter new];
    formatter.locale = [NSLocale localeWithLocaleIdentifier:@"ar"];
    for (NSInteger i = 0; i < 10; i++) {
      NSNumber *num = @(i);
      str = [str stringByReplacingOccurrencesOfString:num.stringValue withString:[formatter stringFromNumber:num]];
    }
    

    Note: this code wrote without IDE, it can be with syntax errors.

提交回复
热议问题