0

I know this is one of the most asked question , but I am not getting how to acually do this. Here is my string ====> @"latitude - 51.50998000 , longitude - -0.13370000".

and I want to extract only the numeric values from it. How can this be achieved? Any ideas?

iCodes
  • 1,382
  • 3
  • 21
  • 47
  • Possible duplicate of: http://stackoverflow.com/questions/8912146/ios-nsstring-retrieving-a-substring-from-a-string – logixologist Nov 23 '13 at 05:53

2 Answers2

0
// Obtaining latitude string
NSString *locationString = @"latitude - 51.50998000 , longitude - -0.13370000";
NSRange latStringRange = NSMakeRange(11, 10);
NSString *latitudeSubstring = [locationString substringWithRange:latStringRange];
NSLog(@"Latitude substring is :- %@",latitudeSubstring);


//Obtaining longitude string
NSString *locString = @"latitude - 51.50998000 , longitude - -0.13370000";
NSRange longsStringRange = NSMakeRange(37, 10);
NSString *longSubstring = [locString substringWithRange:longsStringRange];
NSLog(@"Longitude substring is :- %@",longSubstring);
iCodes
  • 1,382
  • 3
  • 21
  • 47
0

Not perfect solution but something to start with:

NSString *myString = @"latitude - 51.50998000 , longitude - -0.13370000";

/* Formatter is used to convert NSString to NSNumber */
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];

/* Predicate is used to filter array, we need only NSString values with length > 2 */
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"length > 2"];

/* Character set is used to extract only -.0123456789 characters from string */
NSCharacterSet *cSet = [[NSCharacterSet characterSetWithCharactersInString:@"-.0123456789"] invertedSet];

/* Parse latitude and longitude values to NSArray, index 0 will be latitude and index 1 will be longitude */
NSArray *values = [[myString componentsSeparatedByCharactersInSet:cSet] filteredArrayUsingPredicate:predicate];

NSNumber *latitude = [formatter numberFromString:[values objectAtIndex:0]];
NSNumber *longitude = [formatter numberFromString:[values objectAtIndex:1]];

NSLog(@"lat: %f, long: %f", [latitude doubleValue], [longitude doubleValue]);
juniperi
  • 3,723
  • 1
  • 23
  • 30