使用Objective-C中可变数量的空格来生成数组

时间:2010-07-07 04:40:43

标签: objective-c nsstring nsarray

如果单词之间始终是单个空格,那么我将使用这些代码。由于我在某些单词之间有多个空格,因此在使用componentsSeparatedBySring时,如何更改代码以删除多余的空格。我是OBjective-C的新手,所以任何帮助都会非常感激!

这是我的代码: NSString * myString = @“一二三四五”; NSArray * myArray = [myString componentsSeparatedByString:@“”];

2 个答案:

答案 0 :(得分:3)

改为使用NSScanner

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];
}

答案 1 :(得分:0)

+ (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"];