我的以下代码有问题:
NSString *strValue=@"你好";
char temp[200];
strcpy(temp, [strValue UTF8String]);
printf("%s", temp);
NSLog(@"%s", temp);
代码第一行有两个汉字被双引号括起来。问题是 printf 函数可以正确显示汉字,但 NSLog 不能。
Thanks to all. I figured out a solution for this problem. Foundation uses UTF-16 by default, so in order to use NSLog to output the c string in the example, I have to use cStringUsingEncoding to get UTF-16 c string and use %S to replace %s.
NSString *strValue=@"你好";
char temp[200];
strcpy(temp, [strValue UTF8String]);
printf("%s", temp);
strcpy(temp, [strValue cStringUsingEncoding:NSUTF16LittleEndianStringEncoding]);
NSLog(@"%S", temp);
NSLog的%s格式说明符在系统编码中,似乎总是MacRoman而不是unicode,所以它只能显示MacRoman编码的字符。使用 NSLog 的最佳选择是使用本机对象格式说明符 %@ 并直接传递 NSString,而不是将其转换为 C 字符串。如果你只有一个 C 字符串,并且想要使用 NSLog 来显示消息而不是 printf 或 asl,则必须执行 Don 建议的操作,以便首先将字符串转换为 NSString 对象。
因此,所有这些都应该显示预期的字符串:
NSString *str = @"你好";
const char *cstr = [str UTF8String];
NSLog(@"%@", str);
printf("%s\n", cstr);
NSLog(@"%@", [NSString stringWithUTF8String:cstr]);
如果您决定使用 asl,请注意,虽然它接受 UTF8 格式的字符串并将正确的编码传递给 syslog 守护程序(因此它将在控制台中正确显示),但它会在显示到终端时对字符串进行可视化编码或记录到文件句柄,因此非 ASCII 值将显示为转义字符序列。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)