你需要使用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
)