挑战:如何将NSArray数字转换为英文可读列表

时间:2010-08-11 23:05:47

标签: objective-c regex nsstring nsarray integer

我正在寻找一个很好的清洁程序,用于将包含NSNumbers(整数)的NSArray转换为一个漂亮的英文可读字符串。例如,我想改变这个:

[NSArray arrayWithObjects:[NSNumber numberWithInt:5],
                          [NSNumber numberWithInt:7],
                          [NSNumber numberWithInt:12],
                          [NSNumber numberWithInt:33], nil];

进入这个:

  

5,7,12和13。

有没有任何好方法可以做到这一点而没有可怕的if语句逻辑?我确信它可以使用正则表达式完成,但是在iOS 4之前的代码中是否可以这样做?

谢谢! :)

: - 乔

2 个答案:

答案 0 :(得分:4)

NSArray *numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:5],
                          [NSNumber numberWithInt:7],
                          [NSNumber numberWithInt:12],
                          [NSNumber numberWithInt:33], nil];
NSArray *first = [numbers subarrayWithRange:NSMakeRange(0, [numbers count]-1)];
NSString *joined = [[first componentsJoinedByString:@", "] stringByAppendingFormat:(([first count] > 0) ? @"and %@" : @"%@"), [numbers lastObject]];

答案 1 :(得分:2)

看看妈妈,不要错!

NSString *seps[] = {@" and ",@"",@", ",nil,nil,@", "}, *o = @".", *sep = o;
for ( NSNumber *n in [arr reverseObjectEnumerator] ) {
   o = [NSString stringWithFormat:@"%@%@%@",n,sep = seps[[sep length]],o];
}

NSLog(@"out: %@",o);

输出:

out: 5, 7, 12 and 33.

但为什么?

编辑这是一个可以理解的版本,没有“巨大的if / else构造”

NSString *out = @"";  // no numbers = empty string
NSString *sep = @"."; // the separator first used is actually the ending "."
for ( NSNumber *n in [arr reverseObjectEnumerator] )
{
    out = [NSString stringWithFormat:@"%@%@%@",n,sep,out];
    if ( [sep isEqualToString:@"."] ) // was the separator the ending "." ?
    {
        sep = @" and "; // if so, put in the last separator " and "
    } else {
        sep = @", ";    // otherwise, use separator ", "
    }
}

这将输出类似

的字符串
0 elements: ""        (i.e. empty)
1 element:  "33."
2 elements: "12 and 33."
3 elements: "7, 12 and 33."