Split NSString by number of whitespaces

限于喜欢 提交于 2019-12-23 08:59:18

问题


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"}.


回答1:


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 @""



回答2:


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 != ''"]];


来源:https://stackoverflow.com/questions/7537118/split-nsstring-by-number-of-whitespaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!