Converting Unichar to Int Problem

丶灬走出姿态 提交于 2019-12-08 17:41:34

问题


I've got a strange problem trying to convert from unichar to 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

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


回答1:


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.

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


来源:https://stackoverflow.com/questions/4179082/converting-unichar-to-int-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!