NSString componentsSeparatedByString + limit 2013-06-04 14:36:28에 작성. 75,409번 읽힘.

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

이 포스트와 비슷한 포스트들

C# 에서 Time Interval 구하기. 2012-08-07 10:26:22에 작성. 26,095번 읽힘.

DateTime start = DateTime.Now;
//.
//.Your Code
//.
TimeSpan intervalTimespan = DateTime.Now - start;
Console.Log(intervalTimespan.TotalSeconds + " seconds (" + j + " items added) \r\n");

이 포스트와 비슷한 포스트들