2011-09-24 3 views
7

알 수없는 공백 문자로 구분 된 값이 포함 된 NSString이 있습니다. 예를 들어 : {@"1", @"2", @"3"} :공백 개수로 NSString 나누기

NSString* line = @"1 2  3"; 

그래서 같은 값의 NSArrayNSString를 분할하고 싶습니다.

답변

21

@" " 의해 분리 된 구성 요소를 취득하고, 생성 된 어레이로부터 @"" 등 모든 객체를 제거한다.

NSString* line = @"1 2  3"; 
NSMutableArray *array = (NSMutableArray *)[line componentsSeparatedByString:@" "]; 
[array removeObject:@""]; // This removes all objects like @"" 
+0

흥미 롭; 나는 removeObject가 removed * all * 어커런스를 인식하지 못했다. 감사! –

+0

이 용액은보다 깨끗합니다. 고맙습니다. –

+0

Chris Doble, Chris Ledet, 환영합니다! – EmptyStack

4

이것은 (공백을 포함하지 않는 값을 가정)를 달성해야한다 :

// Gives us [@"1", @"2", @"", @"", @"", @"", @"3"]. 
NSArray *values = [line componentsSeparatedByCharactersInSet: 
    [NSCharacterSet whitespaceCharacterSet]]; 

// Remove the empty strings. 
values = [values filteredArrayUsingPredicate: 
    [NSPredicate predicateWithFormat:@"SELF != ''"]];