Chris Ledet
Chris Ledet

Reputation: 11628

Split NSString by number of whitespaces

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

Answers (2)

EmptyStack
EmptyStack

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

user94896
user94896

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

Related Questions