开发者

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

开发者 https://www.devze.com 2023-01-06 11:24 出处:网络
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 sp

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

精彩评论

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