开发者

Challenge: How to turn an NSArray of numbers into an English-readable list

I'm looking for a nice clean routine for turning an NSArray containing NSNumbers (integers) into a nice English-readable string. For example, I want to change this:

[NSArray arrayWithObjects:[NSNumber numberWithInt:5],
                          [NSNumber numberWithInt:7],
                          [NSNumber numberWithInt:12],
                      开发者_Go百科    [NSNumber numberWithInt:33], nil];

into this:

5, 7, 12 and 13.

Is there any nice way of doing this without hideous if statement logic? I'm sure it can be done with a regular expression, but is that possible in pre-iOS 4 code?

Thanks! :)

:-Joe


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]];


Look mom, no ifs!

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);

output:

out: 5, 7, 12 and 33.

but why?

edit here is an understandable version with no "huge if/else construct"

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 ", "
    }
}

This will output strings like

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜