我在 Swift 中解析一个简单的 .txt
文件时遇到了一个奇怪的问题。
文本文件如下:
This is a test \nThis should be on a new line
这是我的代码:
let path = Bundle.main.path(forResource: "test", ofType: "txt")
let example = try? String(contentsOfFile: path!, encoding: .utf8)
let example1 = "This is a test. \nThis should be on a new line."
示例
打印如下:
This is a test \nThis should be on a new line
虽然 example1
打印如下:
This is a test
This should be on a new line
为什么读取文本文件时没有检测到换行符?
最佳答案
你在文件内容中看到的不是肉眼看不到的EOL字符,而是两个字符:“\”和“n”。如果该文件确实有 EOL,它看起来与您声明和打印的字符串的输出相同。
“\n”是一个转义序列,允许您以编程方式在自定义字符串中添加行结尾。编译器将“\n”组合转换为代码为 10 的字符(*nix 平台的 EOL)。这就是您的代码中发生的情况,这就是为什么在打印时字符串具有 EOL。
关于ios - 换行符不适用于 Swift 中的 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48828188/