nsstring - Split string in objective c with number of splits as parameter -
how split below string
"string1:string2:string3:string4:so on.." [0] = "string1" [1] = "string2" [2] = "string3:string4:so on.." in nsstring ? is there way can specify number of splits stop splitting ? or how can achieve scenario ?
try 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 last separator [result addobject:[lastitem substringtoindex:lastitem.length-1]]; return result; }
Comments
Post a Comment