xcode 将 Unichar 转换为 Int 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4179082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting Unichar to Int Problem
提问by fabian789
I've got a strange problem trying to convert from unichar to int:
我在尝试从 unichar 转换为 int 时遇到了一个奇怪的问题:
I have a String containing a few numbers, like @"12345"
. This numbers I want to save individually, meaning I want 5 numbers, 1, 2, 3, ... . Now, while
我有一个包含几个数字的字符串,例如@"12345"
. 我想单独保存这些数字,这意味着我想要 5 个数字,1、2、3、...。现在,同时
NSLog(@"Value: %C", [myString characterAtIndex:0]);
returns
回报
Value: 1
This:
这个:
NSLog(@"Value: %@", [NSNumber numberWithUnsignedChar:[myString characterAtIndex:0]]);
returns
回报
Value: 49
I would really appreciate some help, Fabian
我真的很感激一些帮助,法比安
回答by Chris Parker
In the code above, you're getting exactly what you're asking for; the numeric value of the character '1'
is 49, and you're creating an NSNumber from that.
在上面的代码中,您得到的正是您所要求的;字符的数值'1'
是 49,您正在从中创建一个 NSNumber。
If what you want is 1
, then you can can take advantage of the fact that the digits 0-9 are laid out in order in the ASCII/UTF-8 tables and subtract an appropriate value from the unichar you receive.
如果您想要的是1
,那么您可以利用数字 0-9 在 ASCII/UTF-8 表中按顺序排列的事实,并从您收到的 unichar 中减去一个适当的值。
Try out this code snippet to get you started in the right direction:
试试这个代码片段,让你朝着正确的方向开始:
NSString *s = @"0123456789";
for (int i = 0; i < [s length]; i++) {
NSLog(@"Value: %d", [s characterAtIndex:i]);
}