我有一个NSString类型的数字@"15"
,我想把它转换成NSUInteger类型,但是我不知道怎么做...
我有一个NSString类型的数字@"15"
,我想把它转换成NSUInteger类型,但是我不知道怎么做...
NSString *str = @"15";
// Extract an integer number, returns 0 if there's no valid number at the start of the string.
NSInteger i = [str integerValue];
如果你真的需要一个NSUInteger,只需将其强制转换,但你可能希望在此之前测试一下该值。
NSUInteger i =(NSUInteger)[str integerValue];
- captainpete目前选择的答案对于NSUInteger是不正确的。正如Corey Floyd在所选答案的评论中指出的那样,如果该值大于INT_MAX,则此方法将无效。更好的方法是使用NSNumber,然后使用NSNumber上的方法之一来检索您感兴趣的类型,例如:
NSString *str = @"15"; // Or whatever value you want
NSNumber *number = [NSNumber numberWithLongLong: str.longLongValue];
NSUInteger value = number.unsignedIntegerValue;
在64位系统上,所有这些答案都是错误的。
NSScanner *scanner = [NSScanner scannerWithString:@"15"];
unsigned long long ull;
if (![scanner scanUnsignedLongLong:&ull]) {
ull = 0; // Or handle failure some other way
}
return (NSUInteger)ull; // This happens to work because NSUInteger is the same as unsigned long long at the moment.
测试9223372036854775808,这将无法适应有符号的long long
。
你可以尝试使用 [string longLongValue]
或者 [string intValue]
。