我有一个如下所示的字符串,
I have a string as shown below,
let newString : String = "12","34","56","78","910","1112","1314","1516","1718","1920","2122","2324","2526","2729".
我想用 "4 string each" 字符串分隔字符串,例如12"、34"、56"、78"和910"、1112"、1314"、1516" 等等.
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?
注意:- newString 不是静态数据,它来自网络服务
Note :- newString is not static data it will come from webservice
推荐答案你可以这样尝试,先从 String 创建数组,然后从它创建块数组,然后从数组中加入字符串.
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 = newStringponents(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"]您可以像这样将最后两个动作与单个动作合并.
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"]更多推荐
将字符串拆分为子字符串,组件由字符串 swift 分隔
发布评论