从Swift 3中读取txt文件 [英] Reading from txt file in Swift 3
问题描述
例如,test.txt将包含:
/ b>
<'>'杰森16岁男子自编程
乔什15个男朋友艺术'''
所以我正在寻找一种方法来分别打印每一个单词和一行。如只印刷: 这是我到目前为止搜索到的 感谢您的支持。一旦你把文件读入 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 Thank you for your support. Once you have read your file into
这篇关于从Swift 3中读取txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
杰森
杰森是16$ / b
$ b
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]))
}
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
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])")
}