gpt4 book ai didi

iphone - 如何在不知道编码的情况下读取文本文件

转载 作者:行者123 更新时间:2023-12-03 18:38:42 37 4
gpt4 key购买 nike

当读取在我的应用程序之外其他地方创建的文本文件时,所使用的编码未知。我的应用程序一直在使用 NSUnicodeStringEncoding(与 NSUTF16StringEncoding 相同),因此在读取 UTF16 编码文件以外的文件时遇到问题。

有什么办法可以猜测文件的编码吗?我的首要任务是能够读取 UTF8 文件,然后是所有其他文件。迭代可用的编码并检查读取字符串的长度是否大于零真的是一个好方法吗?

提前致谢。

伊格纳西奥

最佳答案

Apple 的文档提供了有关如何继续操作的一些指导:String Programming Guide: Reading data with an unknown encoding :

If you are forced to guess the encoding (and note that in the absence of explicit information, it is a guess):

  1. 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.

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

  3. 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.

关于iphone - 如何在不知道编码的情况下读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4940527/

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