我想知道如何从txt文件中读取并打印出文件的特定部分?
例如,"test.txt"将包含:
'''杰森16男自我编程
约什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!
}
Run Code Online (Sandbox Code Playgroud)
感谢您的支持.
一旦你阅读了你的文件,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])")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7552 次 |
| 最近记录: |