NSLog编码不正确 [英] NSLog incorrect encoding

查看:73
本文介绍了NSLog编码不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码有问题:

NSString *strValue=@"你好";
char temp[200];
strcpy(temp, [strValue UTF8String]);
printf("%s", temp);
NSLog(@"%s", temp);

在代码的第一行中,两个汉字都用双引号引起来.问题是printf函数可以正确显示中文字符,但NSLog无法显示.


谢谢大家.我想出了解决这个问题的方法. Foundation默认情况下使用UTF-16,因此,为了在示例中使用NSLog输出c字符串,我必须使用cStringUsingEncoding来获取UTF-16 c字符串,并使用%S替换%s.

in the first line of the codes, two Chinese characters are double quoted. The problem is printf function can display the Chinese characters properly, but NSLog can't.


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 String.如果只有C字符串,并且想使用NSLog而不是printf或asl显示消息,则必须执行Don建议的操作,以便首先将字符串转换为NSString对象.

NSLog's %s format specifier is in the system encoding, which seems to always be MacRoman and not unicode, so it can only display characters in MacRoman encoding. Your best option with NSLog is just to use the native object format specifier %@ and pass the NSString directly instead of converting it to a C String. If you only have a C string and you want to use NSLog to display a message instead of printf or asl, you will have to do something like Don suggests in order to convert the string to an NSString object first.

因此,所有这些都应显示预期的字符串:

So, all of these should display the expected string:

NSString *str = @"你好";
const char *cstr = [str UTF8String];
NSLog(@"%@", str);
printf("%s\n", cstr);
NSLog(@"%@", [NSString stringWithUTF8String:cstr]);

如果您决定使用asl,请注意,尽管它接受UTF8格式的字符串并将正确的编码传递给syslog守护程序(这样它将正确显示在控制台中),但它会在显示时对字符串进行编码以进行可视编码到终端或登录到文件句柄,因此非ASCII值将显示为转义的字符序列.

If you do decide to use asl, note that while it accepts strings in UTF8 format and passes the correct encoding to the syslog daemon (so it will show up properly in the console), it encodes the string for visual encoding when displaying to the terminal or logging to a file handle, so non-ASCII values will be displayed as escaped character sequences.

这篇关于NSLog编码不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆