一尘不染

如何转置字符串数组

swift

我有一个txt,其中包含以下格式的一些数据。

AYGA:GKA:GOROKA:GOROKA:PAPUA NEW GUINEA:06:04:54:S:145:23:30:E:5282
AYLA:LAE::LAE:PAPUA NEW GUINEA:00:00:00:U:00:00:00:U:0000
AYMD:MAG:MADANG:MADANG:PAPUA NEW GUINEA:05:12:25:S:145:47:19:E:0020

如何分隔每个用冒号(“:”)区分的项目,以及如何像下面的示例一样将每个部分加载到数组中?

var array1 = ["AYGA", "AYLA", "AYMD"]
var array2 = ["GKA", "LAE", "MAG"]
var array3 = ["GOROKA", "", "MADANG"]
var array4 = ["GOROKA", "LAE", "MADANG"]
var array5 = ["PAPUA NEW GUINEA", "PAPUA NEW GUINEA", "PAPUA NEW GUINEA"]
var array6 = ["06", "00", "05"]
var array7 = ["04", "00", "12"]
var array8 = ["54", "00", "25"]
var array9 = ["S", "U", "S"]
var array10 = ["145", "00", "145"]
var array11 = ["23", "00", "47"]
var array12 = ["30", "00", "19"]
var array13 = ["E", "U", "E"]
var array14 = ["5282", "0000", "0020"]

阅读 275

收藏
2020-07-07

共1个答案

一尘不染

您尝试做的事情称为 换位 。旋转一个看起来像这样的数组:

[[1, 2, 3], [4, 5, 6]]

变成看起来像这样的数组:

[[1, 4], [2, 5], [3, 6]]

为此,让我们定义一个通用的转置函数并将其应用于您的问题

// Import the text file from the bundle

guard
    let inputURL = NSBundle.mainBundle().URLForResource("input", withExtension: "txt"),
    let input = try? String(contentsOfURL: inputURL)
    else { fatalError("Unable to get data") }

// Convert the input string into [[String]]
let strings = input.componentsSeparatedByString("\n").map { (string) -> [String] in
    string.componentsSeparatedByString(":")
}

// Define a generic transpose function.
// This is the key to the solution.

public func transpose<T>(input: [[T]]) -> [[T]] {
    if input.isEmpty { return [[T]]() }
    let count = input[0].count
    var out = [[T]](count: count, repeatedValue: [T]())
    for outer in input {
        for (index, inner) in outer.enumerate() {
            out[index].append(inner)
        }
    }

    return out
}

// Transpose the strings
let results = transpose(strings)

您可以使用看到转置的结果

for result in results {
    print("\(result)")
}

哪个生成(例如)

["AYGA", "AYLA", "AYMD"]
["GKA", "LAE", "MAG"]
["GOROKA", "", "MADANG"]
["GOROKA", "LAE", "MADANG"]
["PAPUA NEW GUINEA", "PAPUA NEW GUINEA", "PAPUA NEW GUINEA"]
["06", "00", "05"]
["04", "00", "12"]
["54", "00", "25"]
["S", "U", "S"]
["145", "00", "145"]
["23", "00", "47"]
["30", "00", "19"]
["E", "U", "E"]
["5282", "0000", "0020"]

这样的优点是不依赖于您拥有的数组数量,而子数组的数量则取自第一个数组的计数。

您可以为此下载一个示例游乐场,该输入在游乐场的资源中作为文件输入。

2020-07-07