从 TXT 中提取 NSString 时出现问题
我正在尝试从文本文件创建一个长字符串。这是我目前拥有的代码。我不太了解编码,我尝试研究但一无所获。这是我的代码行:
NSString* data = [[NSString alloc] initWithContentsOfFile:@"12thnew.txt" encoding: error:NULL];
当我输入编码为 NSASCIIStringEncoding 并要求在 NSLog 中打印字符串时,我得到了 null 错误。请帮忙。谢谢。
I am trying to create one long string from a text file. This is the code that I currently have. I do not really understand the encoding and I tried to research but found nothing. This is the line of code that I have:
NSString* data = [[NSString alloc] initWithContentsOfFile:@"12thnew.txt" encoding: error:NULL];
When I entered the encoding as NSASCIIStringEncoding, and asked to print the string in NSLog I got the null error. Please help. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 NSASCIIStringEncoding 意味着您的文本文件仅包含 0-127 范围内的字符(8 位字符)。您可以在这里阅读: NSString 文档。您很可能想要使用 UTF-8,不是吗?要使用的值是:
NSUTF8StringEncoding
。Using
NSASCIIStringEncoding
means that your text file only contains characters within the 0-127 range (8 bit chars). You can read up on that here: NSString docs. You most likely will want to use UTF-8, no? The value to use is:NSUTF8StringEncoding
.该文件必须具有某种编码。没有 NSString 就无法创建它。在大多数情况下,
NSUTF8StringEncoding
将是正确的选择。它可以正确处理 ASCII 和 UTF-8。您可以使用initWithContentsOfFile:usedEncoding:error:
告诉 Cocoa 自行猜测。The file has to have some encoding. You can't create an NSString without one. In most cases,
NSUTF8StringEncoding
will be the right choice. It handles ASCII correctly as well as UTF-8. You can tell Cocoa to guess for itself by usinginitWithContentsOfFile:usedEncoding:error:
.