gpt4 book ai didi

swift - 在 Swift 3 中读取 txt 文件

转载 作者:搜寻专家 更新时间:2023-10-30 23:05:41 30 4
gpt4 key购买 nike

我想知道如何读取 txt 文件并打印出文件的特定部分?

例如,“test.txt”将包含:

'''Jason 16男自编程

Josh 15男友艺术'''

所以我正在寻找一种方法来分别打印每个单词和行。比如只打印:

“杰森”

“杰森 16 岁”

“乔希喜欢艺术”

这是我到目前为止搜索得到的结果

if let filepath = Bundle.main.path(forResource: "test", ofType: "txt")
{
do
{
let contents = try String(contentsOfFile: filepath)
print(contents[0])

}
catch
{
// contents could not be loaded
}
}
else
{
// example.txt not found!
}

感谢您的支持。

最佳答案

将文件读入contents 后,您可以使用如下代码将其分成行和词:

let lines = contents.components(separatedBy: "\n")
for line in lines {
let words = line.components(separatedBy: " ")
print("\(words[0]) is \(words[1]) and likes \(words[4])")
}

关于swift - 在 Swift 3 中读取 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40822170/

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