Technology

NSString's componentsSeparatedByString Method with a Limit Parameter

Discover how to extend NSString with a custom method to split strings with a specified separator and limit, akin to Java's split and PHP's explode methods.

Sangrak

The componentsSeparatedByString method of NSString is equivalent to Java's split and PHP's explode. Occasionally, there arises the need to set a maximum limit on the splits. As this feature isn't supported natively, below is a custom implementation that has been developed for use.

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']

More on this topic