开发者

componentsSeparatedByCharactersInSet gives me a bunch of empty strings

OK, first and foremost, I am using GNUStep as a way to learn Objective-C, so there may be some differences between the GNU and the Apple implementation. That being said, it shouldn't affect my question.

Anyways, to understand my conundrum, please parse the following code into your visual receptacles:

#import <Cocoa/Cocoa.h>
int main()
{
  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  NSEnumerator * LineEnumerator = [[NSArray arrayWithObjects: @"Jim     1", @"Steve   3", nil] objectEnumerator];
  NSString * s;
  while((s = [LineEnumerator nextObject]))
开发者_开发问答  {
    NSArray * parts = [s componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSLog(@"%@", parts);
  }
  [pool drain];
  return NO;
}

And the following output:

2010-10-07 10:03:50.809 a.out[24512] (Jim, "", "", "", "", 1)
2010-10-07 10:03:50.812 a.out[24512] (Steve, "", "", 3)

My expected output would be:

2010-10-07 10:03:50.809 a.out[24512] (Jim, 1)
2010-10-07 10:03:50.812 a.out[24512] (Steve, 3)

But the componentsSeparatedByCharactersInSet seems to be the only method that comes close to what I am looking for (by the way, I want to be prepared for any mixture of spaces, tabs, or other whitespace characters). Is there an easy way to do this with the standard libraries without writing a new method?


I think you'll have to use NSScanner:

while((s = [LineEnumerator nextObject]))
{
    NSMutableArray *parts = [[NSMutableArray alloc] initWithCapacity:1];

    NSScanner *scanner = [NSScanner scannerWithString:s];
    NSString *token;
    while ([scanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet] intoString:&token]) {
        [parts addObject:token];
    }

    NSLog(@"%@", parts);
    [parts release];
}   


If you don't have newlines why not just use [NSCharacterSet whitespaceCharacterSet] instead?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜