如何通过分隔字符将数组对象拆分为两个(或2d数组)

时间:2016-07-20 08:55:39

标签: arrays swift

我想分割一个如下所示的数组。

let arrayToSplit = ["Europe|#|France|#|Paris", "Europe|#|Italy|#|Rome", "America|#|USA|#|Washington", "America|#|Canada|#|Ottawa"]

let firstArray = ["Europe", "Europe", "America", "America"]
let secondArray = ["France", "Italy", "USA", "Canada"]
let thirdArray = ["Paris", "Rome", "Washington", "Ottawa"]

通过分成这三个数组,我想分割数据收入并将其显示在UITableView中。

3 个答案:

答案 0 :(得分:1)

不是最佳解决方案,但具有预期结果(提示在代码注释中):

Kitten.find().populate({
    path: 'owner'
  , select: 'name'
  , match: { color: 'black' }
  , options: { sort: { name: -1 }}
}).exec(function (err, kittens) {
  console.log(kittens[0].owner.name) // Zoopa
})

// alternatively
Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) {
  console.log(kittens[0].owner.name) // Zoopa
})

答案 1 :(得分:1)

    let arrayToSplit = ["Europe|#|France|#|Paris", "Europe|#|Italy|#|Rome", "America|#|USA|#|Washington", "America|#|Canada|#|Ottawa"]


    print(arrayToSplit)


    let firstArray : NSMutableArray = []
    let secondArray : NSMutableArray = []
    let thirdArray : NSMutableArray = []

    for var i = 0; i < arrayToSplit.count; i++
    {
        let str : String = arrayToSplit[i] as String

         let ary = str.characters.split{$0 == "|"}.map(String.init)

        firstArray.addObject(ary[0])
        secondArray.addObject(ary[2])
        thirdArray.addObject(ary[4])
    }

    print(firstArray)
    print(secondArray)
    print(thirdArray)

答案 2 :(得分:1)

let arrayToSplit = ["Europe|#|France|#|Paris", "Europe|#|Italy|#|Rome", "America|#|USA|#|Washington", "America|#|Canada|#|Ottawa"]

let arrayOfLists = arrayToSplit.map{
    $0.componentsSeparatedByString("|#|")
}

let columns = Array(0..<3).map{ i in
    arrayOfLists.map{ list in list[i]}
}

print(columns)
//[["Europe", "Europe", "America", "America"], ["France", "Italy", "USA", "Canada"], ["Paris", "Rome", "Washington", "Ottawa"]]