开发者

make array out of string with variable number of spaces in Objective-C

This is the code that I would use if it was always single spaces in between words. Since I have multiple spaces in between some words how can my code be changed开发者_如何转开发 to remove the extra spaces when using componentsSeparatedBySring. I'm new to OBjective-C so any help would be greatly appreciated!

Here is my code: NSString *myString = @"One Two Three Four Five"; NSArray *myArray = [myString componentsSeparatedByString: @" "];


Use NSScanner instead:

NSMutableArray *results = [NSMutableArray array];
NSScanner      *scanner = [NSScanner scannerWithString:input];
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@" "];

while ([scanner isAtEnd] == NO) 
{
    NSString *string;
    [scanner scanUpToCharactersFromSet:charSet intoString:&string];
    [results addObject:string];
}


+ (NSArray *)componentsInString:(NSString *)string withSeparacterInString:(NSString *)separaterStr
{
  if (!string || !separaterStr || [separaterStr length] < 1)
    return [NSArray array];

  NSMutableArray *arr = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:separaterStr]] mutableCopy];

  [arr removeObject:@""]; // removes all empty components

  return arr;
}

NSArray *arr = [Utils componentsInString:@"12 123 \n 14 " withSeparacterInString:@" \n"];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜