在目标c中拆分字符串,并将拆分数作为参数

时间:2015-06-19 06:40:51

标签: objective-c nsstring

如何将此分割为字符串

  "string1:string2:string3:string4:so on.." to
    [0] = "string1"
    [1] = "string2"
    [2] = "string3:string4:so on.." in NSString ?

有没有办法可以指定停止分割的分割数量?或者我如何实现这种情况?

1 个答案:

答案 0 :(得分:2)

尝试以下代码:

- (NSArray *)splitString:(NSString *)string withSeparator:(NSString *)separator andMaxSize:(NSUInteger)size {
    NSMutableArray *result = [[NSMutableArray alloc]initWithCapacity:size];
    NSArray *components = [string componentsSeparatedByString:separator];

    if (components.count < size) {
        return components;
    }

    int i=0;
    while (i<size-1) {
        [result addObject:components[i]];
        i++;
    }

    NSMutableString *lastItem = [[NSMutableString alloc] init];
    while (i<components.count) {
        [lastItem appendString:components[i]];
        [lastItem appendString:separator];
        i++;
    }
    // remove the last separator
    [result addObject:[lastItem substringToIndex:lastItem.length-1]];


    return result;
}