【问题标题】:Swift Text File To Array of StringsSwift文本文件到字符串数组
【发布时间】:2015-05-26 20:58:53
【问题描述】:

我想知道将文本文件读入字符串数组的最简单和最干净的方法是 swift。

文本文件:

line 1
line 2
line 3 
line 4

到这样的数组中:

var array = ["line 1","line 2","line 3","line 4"]

我也想知道如何在这样的结构中做类似的事情:

Struct struct{
   var name: String!
   var email: String!
}

所以获取一个文本文件并将其放入数组中的结构中。

感谢您的帮助!

【问题讨论】:

标签: string file swift


【解决方案1】:

这是一种将字符串转换为数组的方法(一旦您阅读了文本):

var myString = "Here is my string"

var myArray : [String] = myString.componentsSeparatedByString(" ")

这将返回具有以下值的字符串数组:["Here", "is", "my", "string"]

【讨论】:

    【解决方案2】:

    首先你必须阅读文件:

    let text = String(contentsOfFile: someFile, encoding: NSUTF8StringEncoding, error: nil)
    

    然后使用componentsSeparatedByString 方法将其逐行分隔:

    let lines : [String] = text.componentsSeparatedByString("\n")
    

    【讨论】:

    • 请注意,有些文件不只是\n 作为换行符。可以考虑使用NSCharacterSet.newlineCharacterSet()componentsSeparatedByCharactersInSet
    • 新的 Swift 语法是:try! let text = String(contentsOfFile: someFile!, encoding: NSUTF8StringEncoding)stackoverflow.com/questions/32663872/…
    【解决方案3】:

    为 Swift 3 更新

        var arrayOfStrings: [String]?
    
        do {
            // This solution assumes  you've got the file in your bundle
            if let path = Bundle.main.path(forResource: "YourTextFilename", ofType: "txt"){
                let data = try String(contentsOfFile:path, encoding: String.Encoding.utf8)                
                arrayOfStrings = data.components(separatedBy: "\n")
                print(arrayOfStrings)
            }
        } catch let err as NSError {
            // do something with Error
            print(err)
        }
    

    【讨论】:

    • 那里有 swift5 的版本吗? :)
    【解决方案4】:

    为 Swift 5 更新:

    const 路径包含文件路径。

    do {
        let path: String = "file.txt"
        let file = try String(contentsOfFile: path)
        let text: [String] = file.components(separatedBy: "\n")
    } catch let error {
        Swift.print("Fatal Error: \(error.localizedDescription)")
    }
    

    如果你想逐行打印file.txt里面的内容:

    for line in text {
        Swift.print(line)
    }
    

    【讨论】:

    • 那里有 swift5 的版本吗? :)
    • 非常感谢! :) 我如何能够将该内容输出到数组中? (一个文本文件,一个数组)
    【解决方案5】:

    在 Swift 3 中,我的工作方式如下:

    Import Foundation
    
    let lines : [String] = contents.components(separatedBy: "\n")
    

    【讨论】:

      【解决方案6】:

      斯威夫特 4:

      do {
          let contents = try String(contentsOfFile: file, encoding: String.Encoding.utf8)
          let lines : [String] = contents.components(separatedBy: "\n")    
      } catch let error as NSError {
          print(error.localizedDescription)
      }
      

      【讨论】:

      • 那里有 swift5 的版本吗? :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多