我想知道如何读取txt文件并打印出文件的特定部分?
例如,“test.txt”将包含:
'''杰森16男自编程
乔什 15 男性朋友艺术'''
所以我正在寻找一种方法来单独打印每个单词和行。比如只打印:
"Jason"
“杰森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])")
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)