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])")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With