从字符串中获取子字符串输出

时间:2012-10-10 11:13:44

标签: iphone objective-c xcode nsstring

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 个答案:

答案 0 :(得分:4)

使用此:

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

答案 1 :(得分:2)

我会做类似......

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

for (NSString *word in words) {
    //check for equals sign and then take the next one.
}

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

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