views:

156

answers:

2

The location text from Twitter could be just about anything. Sometimes Twitter clients set the location with the user's latitude and longitude in the following format.

"\U00dcT: 43.05948,-87.908409"

Since there is no built-in support for Regular Expressions in Objective-C I am considering using the NSString functions like rangeOfString to pull the float values out of this string.

For my current purpose I know the values with start with 43 and 87 so I can key off those values this time but I would prefer to do better than that.

What would you do to parse the latitude/longitude from this string?

A: 

This appears to work well but I am still interested in what other approaches could work better.

- (CLLocation *)parseLocationText:(NSString *)lt {
    // location = "\U00dcT: 43.05948,-87.908409";

    NSString *strippedString = [lt stringByTrimmingCharactersInSet:[NSCharacterSet letterCharacterSet]];
    NSLog(@"strippedString: %@", strippedString);

    if ([strippedString rangeOfString:@","].location != NSNotFound) {
        NSArray *chunks = [strippedString componentsSeparatedByString: @","];
        if (chunks.count == 2) {
            NSLog(@"lat: %@", [chunks objectAtIndex:0]);
            NSLog(@"long: %@", [chunks objectAtIndex:1]);

            NSString *latitude = [chunks objectAtIndex:0];
            NSString *longitude = [chunks objectAtIndex:1];
            CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
            [loc autorelease];
            return loc;
        }
    }

    return nil;
}
Brennan
A: 

This way won't create nearly as many intermediate objects:

float latitude, longitude;
NSString *exampleString = @"\U00dcT: 43.05948,-87.908409";
NSScanner *scanner = [NSScanner scannerWithString:exampleString];
NSCharacterSet *digits = [NSCharacterSet decimalDigitCharacterSet];
[scanner scanUpToCharactersFromSet:digits intoString:null];
[scanner scanFloat:&lattitude];
[scanner scanUpToCharactersFromSet:digits intoString:null];
[scanner scanFloat:&longitude];
NSResponder