How to split array objects into two(or 2d array) by seperation character

后端 未结 3 1130
误落风尘
误落风尘 2021-01-24 22:05

I want to split an array like shown below.

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


        
相关标签:
3条回答
  • 2021-01-24 22:38
    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"]]
    
    0 讨论(0)
  • 2021-01-24 22:39
        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)
    
    0 讨论(0)
  • 2021-01-24 22:45

    Not the best solution, but with the expected result (hints are in the code comments):

    let arrayToSplit = ["Europe|#|France|#|Paris", "Europe|#|Italy|#|Rome", "America|#|USA|#|Washington", "America|#|Canada|#|Ottawa"]
    var firstArray = [String]()
    var secondArray = [String]()
    var thirdArray = [String]()
    
    for element in arrayToSplit {
    
        // new array with substrings divided by "|#|" e.g. ["Europe", "Europe", "America", "America"]
        let newArray = element.componentsSeparatedByString("|#|")
        firstArray.append(newArray[0])
        secondArray.append(newArray[1])
        thirdArray.append(newArray[2])
    }
    
    print("first array: \(firstArray)") // first array: ["Europe", "Europe", "America", "America"]
    print("second array: \(secondArray)") // second array: ["France", "Italy", "USA", "Canada"]
    print("third array: \(thirdArray)") // third array: ["Paris", "Rome", "Washington", "Ottawa"]
    
    0 讨论(0)
提交回复
热议问题