从Swift 3中读取txt文件 [英] Reading from txt file in Swift 3

查看:152
本文介绍了从Swift 3中读取txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如,test.txt将包含:

/ b>

<'>'杰森16岁男子自编程

乔什15个男朋友艺术'''



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

杰森

杰森是16$ / b
$ b Josh喜欢艺术

这是我到目前为止搜索到的

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

}
catch
{
//内容无法加载
}
}
else
{
// example.txt not found!

$ / code>

感谢您的支持。一旦你把文件读入 contents ,你可以用下面的代码把它分解成行和单词: $ b $ pre $ let lines = contents.components(separateBy:\\\

为行{
让words = line.components(separatedBy:)
print(\(words [0])is \(words [1])and likes \(words [4]))
}


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.

解决方案

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

这篇关于从Swift 3中读取txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆