Reputation: 11628
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"}
.
Upvotes: 7
Views: 5393
Reputation: 51374
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 @""
Upvotes: 20
Reputation:
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 != ''"]];
Upvotes: 4