将字符串拆分为子字符串,其中组件由字符串swift分隔

时间:2017-02-09 12:53:31

标签: swift string split substring

我有一个字符串,如下所示,

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

我想将字符串与"4 string each"字符串分开,例如"12","34","56","78" and "910","1112","1314","1516"等等。

我们可以通过使用范围或其他东西实现这一目标吗?

注意: - newString不是来自webservice的静态数据

3 个答案:

答案 0 :(得分:2)

您可以这样尝试,首先从String创建数组,然后从中创建块数组,然后从数组中加入字符串。

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"]

编辑:您可以像这样合并最后两个动作。

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"]

答案 1 :(得分:1)

首先从字符串生成一个数组:

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

然后运行for循环并使用joinWithSeparator

添加字符串

答案 2 :(得分:0)

您可以将,字符串拆分为:let strArr = newString.components(separatedBy: ","),然后将strArr拆分为包含4个元素的数组,并按,加入每个结果数组。希望这有帮助,祝你好运!