7

I have an NSString that contains some values separated by an unknown number of whitespace characters. For example:

NSString* line = @"1 2     3";

I would like to split the NSString into an NSArray of values like so: {@"1", @"2", @"3"}.

Chris Ledet
  • 11,458
  • 7
  • 39
  • 47

2 Answers2

20

Get the components separated by @" " and remove all objects like @"" from the resultant array.

NSString* line = @"1 2     3";
NSMutableArray *array = (NSMutableArray *)[line componentsSeparatedByString:@" "];
[array removeObject:@""]; // This removes all objects like @""
EmptyStack
  • 51,274
  • 23
  • 147
  • 178
4

This should do the trick (assuming the values don't contain whitespace):

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

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