Technology

NSString componentsSeparatedByStringと制限付き分割

NSStringのcomponentsSeparatedByStringメソッドを使用して、指定された限界で文字列を分割する方法について説明します。

Sangrak

NSStringのcomponentsSeparatedByStringメソッドは、JavaのsplitやPHPのexplodeと同様に、文字列を分割するために使用されます。時として、分割する最大限度を設定する必要がある場合がありますが、この機能はデフォルトでは提供されていません。そのため、以下のようにして使っています。

コード

@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

使用法

NSString *text = @"t,e,s,t";
[text componentsSeparatedByString:@"," limit:0]; // 結果: ['t', 'e', 's', 't']
[text componentsSeparatedByString:@"," limit:1]; // 結果: ['t', 'e,s,t']
[text componentsSeparatedByString:@"," limit:2]; // 結果: ['t', 'e', 's,t']
[text componentsSeparatedByString:@"," limit:3]; // 結果: ['t', 'e', 's', 't']
[text componentsSeparatedByString:@"," limit:4]; // 結果: ['t', 'e', 's', 't']

このトピックの関連記事