如何从ios中的字符串中提取子字符串?

时间:2013-11-23 05:50:33

标签: nsstring nsrange

我知道这是最常问的问题之一,但我不知道如何做到这一点。 这是我的字符串====> @"latitude - 51.50998000 , longitude - -0.13370000"

我只想从中提取数值。怎么能实现这一目标?有什么想法吗?

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

不是完美的解决方案,但有些事情要开始:

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]);