Reading from txt file in Swift 3

半世苍凉 提交于 2020-01-03 13:17:13

问题


I want to know how to read from a txt file and print out specific parts of the file?

For example, "test.txt" will contain:

'''Jason 16 male self programing

Josh 15 male friend art'''

So I am looking for a way to print each word and line separately. Such as only printing:

"Jason"

"Jason is 16"

"Josh likes art"

This is what I got so far from searching around

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!
    }

Thank you for your support.


回答1:


Once you have read your file into contents you can break it into lines and words with code like:

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])")
}


来源:https://stackoverflow.com/questions/40822170/reading-from-txt-file-in-swift-3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!