2012-01-23 48 views
0

我需要從GPS座標字符串中提取不同的組件。因此,例如:如何分割Objective C中的GPS座標?

+30° 18' 12" N // pull out 30, 18 & 12 

+10° 11' 1" E // pull out 10, 11 & 1 

-3° 1' 2" S // pull out -3, 1 & 2 

-7° 12' 2" W // pull out -7, 12 & 2 

我曾在網上四處一看,我發現存在NSRegularExpression。我想知道是否有可能以某種方式使用它?我也看了一下提供的文檔,並且試圖將一個正則表達式放在一起,以便將不同的部分拉出來。這是我想出了:

('+'|'-')$n°\s$n'\s$n"\s(N|E|S|W) 

我真的不知道,如果這是正確與否,我還就如何使用它,因爲沒有很多的教程/例如約不清楚。請有人幫我一下嗎?如果有更好的方法來做到這一點,而不是使用NSRegularExpression我對它開放,但據我所知目標c沒有任何內置的正則表達式支持。

回答

2

使用NSScanner:

NSScanner *scanner; 
NSCharacterSet *numbersSet = [NSCharacterSet characterSetWithCharactersInString:@" °'"]; 
int degrees; 
int minutes; 
int seconds; 

NSString *string = @" -7° 12' 2\" W"; 
scanner = [NSScanner scannerWithString:string]; 
[scanner setCharactersToBeSkipped:numbersSet]; 
[scanner scanInt:&degrees]; 
[scanner scanInt:&minutes]; 
[scanner scanInt:&seconds]; 
NSLog(@"degrees: %i, minutes: %i, seconds: %i", degrees, minutes, seconds); 

NSLog輸出:

degrees: -7, minutes: 12, seconds: 2 
4

RegExps是一個矯枉過正的,恕我直言。使用空格作爲分隔符將[NSString componentsSeparatedByString:]分割成若干部分,然後使用[NSString intValue]來挑選除最後一個組件外的每個組件的數值。

0
NSMutableArray *newCoords = [[NSMutableArray alloc] init]; 
NSArray *t = [oldCoords componentsSeparatedByString: @" "]; 

[newCoords addObject: [[t objectAtIndex: 0] intValue]; 
[newCoords addObject: [[t objectAtIndex: 1] intValue]; 
[newCoords addObject: [[t objectAtIndex: 2] intValue]; 

假設你曾在NSString oldCoords在您的文章中給出的座標,這將導致NSMutableArray稱爲newCoords其中將包含數據的三件你所需要的。

2

RE的過度殺傷(Seva)?對象如何? ;-)

NSString *coords = @"+30° 18' 12\" N"; 

int deg, sec, min; 
char dir; 

if(sscanf([coords UTF8String], "%d° %d' %d\" %c", &deg, &min, &sec, &dir) != 4) 
    NSLog(@"Bad format: %@\n", coords); 
else 
    NSLog(@"Parsed %d deg, %d min, %d sec, dir %c\n", deg, min, sec, dir); 

不管你喜歡這個取決於你放入C的視圖,但它是直接和簡單的。

0

需要重新是:@"([+-]?[0-9]+)"

下面是示例代碼:

NSString *string; 
NSString *pattern; 
NSRegularExpression *regex; 
NSArray *matches; 

pattern = @"([+-]?[0-9]+)"; 

regex = [NSRegularExpression 
     regularExpressionWithPattern:pattern 
     options:NSRegularExpressionCaseInsensitive 
     error:nil]; 

string = @" -7° 12' 2\" W"; 
NSLog(@"%@", string); 
matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])]; 
degrees = [[string substringWithRange:[[matches objectAtIndex:0] range]] intValue]; 
minutes = [[string substringWithRange:[[matches objectAtIndex:1] range]] intValue]; 
seconds = [[string substringWithRange:[[matches objectAtIndex:2] range]] intValue]; 
NSLog(@"degrees: %i, minutes: %i, seconds: %i", degrees, minutes, seconds); 

的NSLog輸出:

度:-7,分鐘:12,秒:2