NSString componentsSeparatedByString + limit While이 에 작성. 75,408번 읽힘.
NSString 의 componentsSeparatedByString 메소드는 자바의 split, PHP의 explode 와 동일하다. 가끔 split 할 최대 limit 을 설정하는게 필요 할 때가 있다. 자체 기능은 지원하지 않으므로 아래와 같이 만들어 쓰고 있다.
Code
@interface NSString (Split) - (NSArray *)componentsSeparatedByString:(NSString *)separator limit:(NSUInteger)limit; @end @implementation NSString (Split) - (NSArray *)componentsSeparatedByString:(NSString *)separator limit:(NSUInteger)limit { if (limit == 0) return [self componentsSeparatedByString:separator]; NSArray *splited = [self componentsSeparatedByString:separator]; NSMutableArray *newArray = [NSMutableArray array]; int i = 0; for (NSString *str in splited) { if (i >= limit) { NSString *joinAfter = [[splited subarrayWithRange:NSMakeRange(i, [splited count] - i)] componentsJoinedByString:separator]; [newArray addObject:joinAfter]; break; } [newArray addObject:str]; i++; } return newArray; } @end
Usage
NSString *text = @"t,e,s,t"; [text componentsSeparatedByString:@"," limit:0]; // result: ['t', 'e', 's', 't'] [text componentsSeparatedByString:@"," limit:1]; // result: ['t', 'e,s,t'] [text componentsSeparatedByString:@"," limit:2]; // result: ['t', 'e', 's,t'] [text componentsSeparatedByString:@"," limit:3]; // result: ['t', 'e', 's', 't'] [text componentsSeparatedByString:@"," limit:4]; // result: ['t', 'e', 's', 't']