将字符串拆分为子字符串,组件由字符串 swift 分隔 [英] Split string into substring with component separated by string swift

查看:51
本文介绍了将字符串拆分为子字符串,组件由字符串 swift 分隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

您可以像这样将最后两个动作与单个动作合并.

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 分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆