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

编程入门 行业动态 更新时间:2024-10-26 18:26:57
本文介绍了将字符串拆分为子字符串,组件由字符串 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 = 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 分隔

本文发布于:2023-10-26 22:06:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531482.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   组件   swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!