gpt4 book ai didi

iphone - 来自编码未知的文本文件的 NSString

转载 作者:行者123 更新时间:2023-12-01 16:52:18 24 4
gpt4 key购买 nike

我正在尝试根据 Apple 的文档显示编码未知的文本文件的内容:

Try stringWithContentsOfFile:usedEncoding:error: or initWithContentsOfFile:usedEncoding:error: (or the URL-based equivalents). These methods try to determine the encoding of the resource, and if successful return by reference the encoding used.

If (1) fails, try to read the resource by specifying UTF-8 as the encoding.

If (2) fails, try an appropriate legacy encoding. "Appropriate" here depends a bit on circumstances; it might be the default C string encoding, it might be ISO or Windows Latin 1, or something else, depending on where your data is coming from.

这并不总是有效。是否有更可靠的方法来检测编码?

最佳答案

您应该使用可以检测编码的 NSAttributedString。经过长时间测试不同的解决方案后,我使用了:

NSError *error;
NSDictionary *options = [NSDictionary dictionary];
NSDictionary *attributes;
NSAttributedString *theString = [[NSAttributedString alloc] initWithURL:fileURL options:options documentAttributes:&attributes error:&error];
NSInteger detectedEncoding = [[attributes objectForKey:@"CharacterEncoding"] integerValue];

我测试了来自许多来源/环境的许多文件,它似乎是有效的(因此你应该检查 error 是否为 nil )。对于从 Excel 导出的普通 csv 文件,我得到了这个属性字典(30 值表示 NSMacOSRomanStringEncoding:

{
CharacterEncoding = 30;
DocumentType = NSPlainText;
UTI = "public.plain-text";
}

关于iphone - 来自编码未知的文本文件的 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14621969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com