将Unichar转换为Int问题 [英] Converting Unichar to Int Problem
问题描述
尝试将unichar转换为int时遇到一个奇怪的问题:
I've got a strange problem trying to convert from unichar to int:
我有一个包含一些数字的字符串,例如@"12345"
.我要单独保存此数字,这意味着我需要5个数字,1、2、3,....现在,
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
NSLog(@"Value: %C", [myString characterAtIndex:0]);
返回
Value: 1
此:
NSLog(@"Value: %@", [NSNumber numberWithUnsignedChar:[myString characterAtIndex:0]]);
返回
Value: 49
真的很感谢Fabian
I would really appreciate some help, Fabian
推荐答案
在上面的代码中,您所得到的正是您想要的;字符'1'
的数字值为49,您正在从中创建一个NSNumber.
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
,则可以利用以下事实:将0-9数字按顺序排列在ASCII/UTF-8表中,并从收到的unichar中减去适当的值
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.
请尝试以下代码片段,以帮助您正确地开始工作:
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]);
}
这篇关于将Unichar转换为Int问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!