2012-10-10 196 views
0
1 US Dollar = 3.673 United Arab Emirates Dirham 

如何從此字符串獲取值3.673從字符串中獲取子字符串

我試過下面的代碼,但沒有工作。

NSString *a = [[xmlParser array]objectAtIndex:2]; 
NSRange startRange = [a rangeOfString:@"="]; 
NSLog(@"%u",startRange.location+1); 
NSRange endRange = [a rangeOfString:@" "]; 
NSLog(@"%u",endRange.location); 
NSString *subString = [a substringWithRange:NSMakeRange(startRange.location + 1, endRange.location)]; 
NSLog(@"%@",subString); 

回答

4

使用此:

NSArray *aArray = [a componentsSeparatedByString:@" "]; //your string here 
NSString *dollarValue = [aArray objectAtIndex:4]; //get dollar value from array 
NSLog(@"%@",dollarValue); 
+1

是的,這是比我的更好,如果你知道你想要的值始終是句子中的第5個(索引4)字。 – Fogmeister

+0

它早期工作正常,但突然我的應用程序崩潰我得到的錯誤在第一行和日誌說。***終止應用程序由於未捕獲的異常'NSInvalidArgumentException',原因:' - [CurrencyValues componentsSeparatedByString:]:無法識別的選擇器發送到實例0x5913d00' – Sekhar

2

我會做這樣的事情......

NSArray *words = [string componentsSeparatedByString:@" "]; 

for (NSString *word in words) { 
    //check for equals sign and then take the next one. 
} 
0
NSString *param = nil; 
    NSRange start = [a rangeOfString:@"="]; 
    if (start.location != NSNotFound) 
    { 
     param = [a substringFromIndex:start.location + start.length]; 
     NSRange end = [param rangeOfString:@"United"]; 
     if (end.location != NSNotFound) 
     { 
      param = [param substringToIndex:end.location]; 
     } 
    } 
    NSLog(@"param: %@",param); 
1
str = [NSString stringWithFormat:@"1 US Dollar = 3.673 United Arab Emirates Dirham"]; 
components = [str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 
str = [components objectAtIndex:4]; 
NSLog(@"Str:%@", str); 
相關問題