NSString 到 NSUInteger

发布于 2024-08-30 14:44:23 字数 79 浏览 3 评论 0原文

我在 NSString @"15" 中有一个数字。我想将其转换为 NSUInteger,但我不知道该怎么做......

I've got a number in a NSString @"15". I want to convert this to NSUInteger, but I don't know how to do that...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

七颜 2024-09-06 14:44:23
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,只需转换它即可,但您可能需要事先测试该值。

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];

If you really want an NSUInteger, just cast it, but you may want to test the value beforehand.

瀟灑尐姊 2024-09-06 14:44:23

当前选择的答案对于 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;

The currently chosen answer is incorrect for NSUInteger. As Corey Floyd points out a comment on the selected answer this won't work if the value is larger than INT_MAX. A better way of doing this is to use NSNumber and then using one of the methods on NSNumber to retrieve the type you're interested in, e.g.:

NSString *str = @"15"; // Or whatever value you want
NSNumber *number = [NSNumber numberWithLongLong: str.longLongValue];
NSUInteger value = number.unsignedIntegerValue;
梦行七里 2024-09-06 14:44:23

所有这些答案在 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

All these answers are wrong on a 64-bit system.

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.

Test with 9223372036854775808, which won't fit in a signed long long.

李白 2024-09-06 14:44:23

您可以尝试使用 [string longLongValue][string intValue]..

you can try with [string longLongValue] or [string intValue]..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文