开发者

Converting Unichar to Int Problem

开发者 https://www.devze.com 2023-01-25 05:38 出处:网络
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,

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 appreci开发者_开发问答ate some help, Fabian


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

精彩评论

暂无评论...
验证码 换一张
取 消