tags:

views:

17

answers:

2

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?

A: 

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

ExitToShell
Eh, it's just what happened to be in the source code at the time, after trying different things. One or the other, it doesn't seem to make any difference to the output.
Richard Hoffman
+2  A: 

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];
}   
aBitObvious
Thanks, I wasn't aware of this class, you've been a big help.
Richard Hoffman