Split string into substring with component separat

2019-09-22 04:54发布

问题:

I have a string as shown below,

let newString : String = "12","34","56","78","910","1112","1314","1516","1718","1920","2122","2324","2526","2729".

i want to separate string with "4 string each" string e.g. "12","34","56","78" and "910","1112","1314","1516" and so on.

Can we achieve this by using range or something else?

Note :- newString is not static data it will come from webservice

回答1:

You can try like this way, first create array from String, then make chunk array from it and then join the string from array.

let newString = "1,2,3,4,5,6,7,8,9,10,11,12"
let array = newString.components(separatedBy: ",") // ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
let chunkSize = 4
let chunksArray = stride(from: 0, to: array.count, by: chunkSize).map {
    Array(array[$0..<min($0 + chunkSize, array.count)])
}
let subArray = chunksArray.map { $0.joined(separator: ",") }
// ["1,2,3,4", "5,6,7,8", "9,10,11,12"]

Edit: You can merge last two action with single like this way.

let subArray = stride(from: 0, to: array.count, by: chunkSize).map { 
    array[$0..<min($0 + chunkSize, array.count)].joined(separator: ",") 
}
// ["1,2,3,4", "5,6,7,8", "9,10,11,12"]


回答2:

First generate an array from string:

let newString = "1,2,3,4,1234,1235,1236,1238,678,679"    
let newStringArray = newString.componentsSeparatedByString(",")

Then run for loop and add string using joinWithSeparator



回答3:

You could split string the by , like: let strArr = newString.components(separatedBy: ","), then split the strArr to arrays containing 4 elements, and join each resulting array by ,. Hope this helps, good luck!