在objective-c中将1转换为“One”等的算法

时间:2015-07-10 12:51:10

标签: objective-c

我正在寻找一种算法或函数来将整数0,1,2分别转换为零,一,二。我们怎么能在Objective-C中做到这一点?

2 个答案:

答案 0 :(得分:4)

Apple为许多数据类型内置了许多方便的格式化功能。它们被称为“格式化程序”,可以将对象转换为字符串表示形式。

对于您的情况,您将使用NSNumberFormatter,但如果您有一个整数,则需要先将其转换为NSNumber。见下面的例子。

NSInteger anInt = 11242043;
NSString *wordNumber;

//convert to words
NSNumber *numberValue = [NSNumber numberWithInt:anInt]; //needs to be NSNumber!
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterSpellOutStyle];
wordNumber = [numberFormatter stringFromNumber:numberValue];
NSLog(@"Answer: %@", wordNumber);
// Answer: eleven million two hundred forty-two thousand forty-three

答案 1 :(得分:1)

这是我的0到100的代码(您可以根据您的要求进行更新)。工作完美!!

-(NSDictionary *)algorithm
{
    NSArray *myArray = @[@"Zero",@"One",@"Two",@"Three",@"Four",@"Five",@"Six",@"Seven",@"Eight",@"Nine",@"Ten",@"Eleven",@"Twelve",@"Thirteen",@"Fourteen",@"Fifteen",@"Sixteen",@"Sevteen",@"Eighteen",@"Nineteen"];

    NSArray *tensArray = @[@"Twenty",@"Thirty",@"Fourty",@"Fifty",@"Sixty"
                           ,@"Seventy",@"Eighty",@"Ninety",@"One Hundred"];

    NSMutableDictionary *numberStringDictionary = [[NSMutableDictionary alloc] init];

    NSMutableArray *numberStringsArray = [[NSMutableArray alloc] init];

    for(int i=0;i<=100;i++)
    {

        if(i<20)
        {
            [numberStringDictionary setObject:myArray[i] forKey:[NSString stringWithFormat:@"%d",i]];
            [numberStringsArray addObject:myArray[i]];
            NSLog(@"\n%@",myArray[i]);
        }
        else if(i%10==0)
        {
            [numberStringDictionary setObject:tensArray[i/10-2] forKey:[NSString stringWithFormat:@"%d",i]];
            [numberStringsArray addObject:tensArray[i/10-2]];
            NSLog(@"\n%@",tensArray[i/10-2]);
        }
        else
        {
            [numberStringDictionary setObject:[NSString stringWithFormat:@"%@ %@",tensArray[i/10-2],myArray[i%10]] forKey:[NSString stringWithFormat:@"%d",i]];

            [numberStringsArray addObject:[NSString stringWithFormat:@"%@ %@",tensArray[i/10-2],myArray[i%10]]];

            NSLog(@"%@",[NSString stringWithFormat:@"%@ %@",tensArray[i/10-2],myArray[i%10]]);
        }

    }
    return numberStringDictionary;
}