How to transpose an array of strings

前端 未结 3 544
伪装坚强ぢ
伪装坚强ぢ 2020-12-20 20:23

I\'ve a txt including some data in the following format.

AYGA:GKA:GOROKA:GOROKA:PAPUA NEW GUINEA:06:04:54:S:145:23:30:E:5282
AYLA:LAE::LAE:PAPUA NEW GUINEA:0         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-20 21:14

    Here is another alternative that handles different newline characters well and doesn't require any hard coding to get the correct number of arrays. The number of colon-separated components is read from the first line.

    let input = "AYGA:GKA:GOROKA:GOROKA:PAPUA NEW GUINEA:06:04:54:S:145:23:30:E:5282\nAYLA:LAE::LAE:PAPUA NEW GUINEA:00:00:00:U:00:00:00:U:0000\nAYMD:MAG:MADANG:MADANG:PAPUA NEW GUINEA:05:12:25:S:145:47:19:E:0020"
    var arrays: [[String]]?
    input.enumerateLines { (line, _) in
        let chunks = line.componentsSeparatedByString(":")
    
        if arrays == nil {
            arrays = [[String]](count: chunks.count, repeatedValue: [String]())
        }
    
        chunks.enumerate().forEach { item in
            arrays?[item.index].append(item.element)
        }
    }
    

提交回复
热议问题