Using NSScanner to scan up to and include the separator character?

Go To StackoverFlow.com

1

I have a string that's basically dates into a string with extra whitespace in some areas for formatting when showing the string. So the string can look something like

6:00 PM 
6:00 PM  4:00 AM
6:00 PM  4:00 AM 12:00 PM
6:00 pm  4:00 AM 12:00 PM  1:00 AM

I figured I could use NSScanner to parse the string by the @"M" since sometimes there are two spaces between times, sometimes a single space, etc. So what I did was:

    NSScanner *theScanner = [NSScanner scannerWithString:theString];
    NSString *separatorString = @"M";
    NSString *container;
    NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:_lastIndexPath.row];

    while ([theScanner isAtEnd] == NO) {
        [theScanner scanUpToString:separatorString intoString:&container];
        [array addObject:container];

        [theScanner setScanLocation:[theScanner scanLocation] + 1];
    }

The problem is I do not get the M in my container object since it scans up to but it doesn't include the separator string. Should I just manually create a new NSString before adding it like

[array addObject:[NSString stringWithFormat:%@M", container]];

Or is there a better way to use NSScanner in this scenario? I really haven't used NSScanner before. Thanks.

2012-04-04 05:38
by Crystal


5

That would work. But when the last M is encountered and you set your scanner location to +1, it will go out of bounds!? Be careful of that.

Did you consider using the NSString instance methods?

- (NSArray *)componentsSeparatedByString:(NSString *)separator and

- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator

An alternative is that - You could separate your string into components, separated by single space, getting those components in an array. In cases where there would be more than single space, some components will have space(s) at the start or end. You could trim those.

Example:

NSString *list = @"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:@", "];
produces an array { @"Norman", @"Stanley", @"Fletcher" }.

For detailed description of these methods, refer the NSString Class Reference

2012-04-04 06:12
by NoName
Ads