San*_*tix 2 objective-c unichar
我有一个NSString对象,并希望将其更改为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(@"%@",chineseChar);
Run Code Online (Sandbox Code Playgroud)
当我看到日志时,每次运行代码时它都会给出不同的字符.我错过了什么......?
该%C格式说明需要一个16位的Unicode字符(unichar)作为输入,而不是一个NSString.你正在传入一个NSString,它被重新解释为一个整数字符; 由于每次运行时字符串都可以存储在内存中的不同地址,因此您将该地址作为整数获取,这就是每次运行代码时都会得到不同的中文字符的原因.
只需将字符作为整数传入:
unichar decimal = 12298;
NSString *charStr = [NSString stringWithFormat:@"%C", decimal];
// charStr is now a string containing the single character U+300A,
// LEFT DOUBLE ANGLE BRACKET
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3572 次 |
| 最近记录: |