Split string in objective c with number of splits as parameter

105 Views Asked by At

How to split this below string

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

Is there a way I can specify the number of splits for which it will stop splitting ? OR How can i achieve this scenario ?

1

There are 1 best solutions below

1
On

try the following code:

- (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;
}