开发者

is it possible to convert NSString into unichar

I have a NSString object and want to change it into unichar.

int decimal = [[temp substringFromIndex:2] intValue]; // decimal = 12298

NSString *hex = [NSString stringWithFormat:@"0x%x", decimal]; // hex = 0x300a

NSString *chineseChar = [NSString stringWithFormat:@"%C", hex];

// This statement log a different Chinese char every time I run this code 
NSLog开发者_如何学Python(@"%@",chineseChar); 

When I see the log, It gives different character every time when I run my code. m I missing something...?


The %C format specifier takes a 16-bit Unicode character (unichar) as input, not an NSString. You're passing in an NSString, which is getting reinterpreted as an integer character; since the string can be stored at a different address in memory each time you run, you get that address as an integer, which is why you get a different Chinese character every time you run your code.

Just pass in the character as an integer:

unichar decimal = 12298;
NSString *charStr = [NSString stringWithFormat:@"%C", decimal];
// charStr is now a string containing the single character U+300A,
// LEFT DOUBLE ANGLE BRACKET


How about -[NSString characterAtIndex:]? It wants a character index and returns a unichar.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜