如何在Objective-C中将字符串中的英语数字转换为波斯/阿拉伯数字? [英] How to convert english numbers inside a string to Persian/Arabic numbers in Objective-C?
本文介绍了如何在Objective-C中将字符串中的英语数字转换为波斯/阿拉伯数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个英文字符串,可能有也可能没有数字.但是我希望这些数字作为波斯数字印在屏幕上.
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.
例如,如果NSString *foo = @"a string with numbers 1 2 3;"
则输出应为a string with numbers ۱۲۳
我现在正在使用的代码是:
The code I'm using right now is :
-(NSString *)convertEnNumberToFarsi:(NSString *) number{
NSString *text;
NSDecimalNumber *someNumber = [NSDecimalNumber decimalNumberWithString:number];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"fa"];
[formatter setLocale:gbLocale];
text = [formatter stringFromNumber:someNumber];
return text;
}
此方法仅转换仅包含数字的字符串,但是如上所述,我想转换其中可能包含或不包含数字的任何字符串.
This method only converts a string that is only in numbers, but as mentioned above i want to convert any string that may or may not have numbers in it.
我该如何实现?
推荐答案
简单方法:
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]];
}
注意:此代码是在没有IDE的情况下编写的,可能存在语法错误.
这篇关于如何在Objective-C中将字符串中的英语数字转换为波斯/阿拉伯数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文