Objective c NSLog错误编码
我对以下代码有问题:Objective c NSLog错误编码,objective-c,Objective C,我对以下代码有问题: NSString *strValue=@"你好"; char temp[200]; strcpy(temp, [strValue UTF8String]); printf("%s", temp); NSLog(@"%s", temp); 在代码的第一行,两个汉字被双引号引起来。问题是printf函数可以正确显示汉字,但NSLog不能。 谢谢大家。我想出了解决这个问题的办法。基金会默认使用UTF16,所以为了在示例中使用NSLAST输出C字符串,我必须使用CSTRUGUS
NSString *strValue=@"你好";
char temp[200];
strcpy(temp, [strValue UTF8String]);
printf("%s", temp);
NSLog(@"%s", temp);
在代码的第一行,两个汉字被双引号引起来。问题是printf函数可以正确显示汉字,但NSLog不能。
谢谢大家。我想出了解决这个问题的办法。基金会默认使用UTF16,所以为了在示例中使用NSLAST输出C字符串,我必须使用CSTRUGUSEN编码来获取UTF16C字符串,并使用%s替换%s。p>
NSString *strValue=@"你好";
char temp[200];
strcpy(temp, [strValue UTF8String]);
printf("%s", temp);
strcpy(temp, [strValue cStringUsingEncoding:NSUTF16LittleEndianStringEncoding]);
NSLog(@"%S", temp);
我知道你可能在寻找一个能帮助你理解事情发展的答案 但这就是你现在可以做的来解决你的问题:
NSLog(@"%@", strValue);
我的猜测是,NSLog假定8位C字符串的编码与UTF-8不同,并且可能不支持汉字。虽然很尴尬,但您可以尝试以下方法:
NSLog(@"%@", [NSString stringWithCString: temp encoding: NSUTF8StringEncoding]);
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值将显示为转义字符序列。好方法:-)它是否可以处理
#
和定义之间的空格?另外,也许一行解释可能会有帮助,因为代码行很长,因此可读性不好。@peter_the_oak适合我
# define NSLogUTF8(a,b) NSLog(a,[NSString stringWithCString:[[NSString stringWithFormat:@"%@",b] cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding])
#define NSLogUTF8Ex(a,b) NSLog(a,[MLTool utf8toNString:[NSString stringWithFormat:@"%@",b]])
+(NSString*)utf8toNString:(NSString*)str{
NSString* strT= [str stringByReplacingOccurrencesOfString:@"\\U" withString:@"\\u"];
//NSString *strT = [strTemp mutableCopy];
CFStringRef transform = CFSTR("Any-Hex/Java");
CFStringTransform((__bridge CFMutableStringRef)strT, NULL, transform, YES);
return strT;
}