-4

我需要从这样的字符串(“5, 15, 7-10”)和符号中获取符号,直到第一个逗号需要写入第一个字符串,直到第二个字符串和分隔破折号的符号需要写入数组重新计算第一个到最后一个的值。

4

1 回答 1

1

您需要使用 componentSeparatedByString:

NSString *list = @"5, 15, 7-10";
NSArray *listItems = [list componentsSeparatedByString:@", "];

这将返回一个看起来像的数组@[@"5", @"15", @"7-10"];

根据我对您问题的理解,这应该可行。不过,您可能想完善您的问题,因为它有点难以弄清楚。如果您这样做并且我所做的不起作用,我很乐意解决该解决方案。

编辑:以下代码可以满足您的要求(我认为):

NSString *list = @"5, 15, 7-10";
NSArray *listItems = [list componentsSeparatedByString:@", "];
NSMutableArray *expandedList = [[NSMutableArray alloc] init];

for(NSString *s in listItems){
    NSRange found = [s rangeOfString:@"-"];
    if (found.location == 1) {
        NSArray *hyphenString = [s componentsSeparatedByString:@"-"];
        NSInteger first = [[hyphenString objectAtIndex:0] intValue];
        NSInteger last = [[hyphenString objectAtIndex:1] intValue];
        [expandedList addObject:@(first)];
        NSInteger trueDiff = (last - first) - 1;
        int i = 0;
        while (i < trueDiff){
            first = first + 1;
            [expandedList addObject:@(first)];
            i++;
        }
        [expandedList addObject:@(last)];

    } else {
        [expandedList addObject:[NSNumber numberWithInt:[s intValue]]];
    }
}
NSLog(@"%@", expandedList);

这将输出:

2013-08-17 21:12:54.579 NumWork[693:303] (
    5,
    15,
    7,
    8,
    9,
    10
)
于 2013-08-18T00:03:56.617 回答