如何从NSString获取int?

时间:2013-06-26 01:41:10

标签: ios objective-c nsstring

更新

我不想使用XML解析器,因为这是所有字符串。非常小,所以,请不要解析器。感谢。


我有一个像这样的XML字符串:<AppVersion>5</AppVersion>。现在我想得到5。怎么办?

请注意,5也可以是50。我的意思是长度会改变。

3 个答案:

答案 0 :(得分:4)

您可以使用正则表达式:

NSString *string = @"<AppVersion>50</AppVersion>";
NSError *error;

// this looks for any sequence of digits between 0 and 9 between those two tags

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<AppVersion>([0-9]+)</AppVersion>"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];
if (error)
    NSLog(@"%s: regularExpressionWithPattern error: %@", __FUNCTION__, error);

NSTextCheckingResult *match = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
NSRange range = [match rangeAtIndex:1];
if (range.location != NSNotFound)
{
    NSString *result = [string substringWithRange:range];
    NSLog(@"%@", result);
}

或者您可以使用扫描仪:

NSScanner *scanner = [NSScanner scannerWithString:string];
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:nil];
NSInteger i;
if ([scanner scanInteger:&i])
    NSLog(@"%d", i);

答案 1 :(得分:1)

我假设你有字符串并且正在寻找一种简单的方法来提取数字。这可以通过几行代码完成。我们知道起点,因为它是一个常数。结束点可能因数字的长度而异。

NSString *xml=@"<AppVersion>5</AppVersion>";
int start=12; // Constant
NSRange end = [xml rangeOfString:@"</"]; // Depends on length

NSString *aNum = [xml substringWithRange:NSMakeRange(start, end.location-start)];
NSLog(@"%@", aNum);

NSString *xml=@"<AppVersion>5</AppVersion>"; int start=12; // Constant NSRange end = [xml rangeOfString:@"</"]; // Depends on length NSString *aNum = [xml substringWithRange:NSMakeRange(start, end.location-start)]; NSLog(@"%@", aNum);

三个例子表明它适用于一般情况:

// Test 5
NSString *xml=@"<AppVersion>5</AppVersion>";
int start=12; // Constant
NSRange end = [xml rangeOfString:@"</"]; // Depends on length

NSString *aNum = [xml substringWithRange:NSMakeRange(start, end.location-start)];
NSLog(@"%@", aNum);

// Test 500
xml=@"<AppVersion>500</AppVersion>";
end = [xml rangeOfString:@"</"]; // Depends on length

aNum = [xml substringWithRange:NSMakeRange(start, end.location-start)];
NSLog(@"%@", aNum);

// Test 500000
xml=@"<AppVersion>500000</AppVersion>";
end = [xml rangeOfString:@"</"]; // Depends on length

aNum = [xml substringWithRange:NSMakeRange(start, end.location-start)];
NSLog(@"%@", aNum);

答案 2 :(得分:0)

我有自己的类别来从XML获取价值 但您可以尝试使用NSXMLParser