要从一个txt文件填充字符串数组 [英] Fill an array with strings from a txt file

查看:173
本文介绍了要从一个txt文件填充字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DATA.TXT包含这样的东西:


鼠标

Data.txt contains stuff like this : "Cat" "Dog" "Mouse"

我要填充的字符串数组从文件(DICO [0] =猫,迪科[1] =狗,ASO)。

I want to fill an array with strings from that file (dico[0] = "Cat", dico[1] = "Dog", aso).

我发现这一点,<一个href=\"http://stackoverflow.com/questions/24268945/how-to-call-objective-cs-nsarray-class-method-from-within-swift\">How内斯威夫特从调用的Objective-C的NSArray的类方法?和阅读和写入文本文件数据,但是当我用这个code:

I found this, How to call Objective-C's NSArray class method from within Swift? and Read and write data from text file, but when I use this code :

let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("data", ofType: "txt")
let dico = NSArray(contentsOfFile: path)

println("\(dico[0])")
println("\(dico.count)")

我得到的是无和0。

All I get is "nil" and "0".

我想在我的文件不会被写入他们应该是道路,code我用的数据是不正确的,但我不明白为什么。

I guess data in my file aren't written the way they should be and the code I use isn't right, but I can't figure why.

此外,当我用这个code,这是确定:

Moreover, when I use this code, it's OK :

    let bundle = NSBundle.mainBundle()
    let path = bundle.pathForResource("data", ofType: "txt")
    let dico = NSString(contentsOfFile: path)

    println("\(dico)")

问题是,我不希望给DICO是一个字符串,我希望它是一个数组。

The problem is that I don't want dico to be a string, I want it to be an array.

推荐答案

这是不是如何 arrayWithContentsOfFile

据预计,作为它的参数的路径,包含字符串再由将writeToFile产生的数组presentation文件:原子:

It expects as its argument the path to a file containing a string representation of an array produced by the writeToFile:atomically: method.

你的目的,你可以使用第二种方法,通过调用 componentsSeparatedByString()在您的字符串补充。

For your purposes, you can use the second approach, complemented by calling componentsSeparatedByString() on your string.

let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("data", ofType: "txt")
let dico = NSString(contentsOfFile: path).componentsSeparatedByString("\n")

这篇关于要从一个txt文件填充字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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