Swift3.0 split函数切割字符串
我们先看函数的原型:
- public func split(separator: Self.Iterator.Element, maxSplits: Int = default, omittingEmptySubsequences: Bool = default) -> [Self.SubSequence]
第一个参数就不用解释了,传入要切割的字符串,像这样
- let line = "BLANCHE: I don't want realism. I want magic!"
- print(line.characters.split(separator: " ")
- .map(String.init))
- // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
下面看第二个参数,像这样,意思是切割几次,设置为1的话就把原来的字符串切成两个。
- // The second example passes `1` for the `maxSplits` parameter, so the
- // original string is split just once, into two new strings.
- print(line.characters.split(separator: " ", maxSplits: 1)
- .map(String.init))
- // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
第三个参数就很明确了,是否保留隐藏字符
- // The final example passes `false` for the `omittingEmptySubsequences`
- // parameter, so the returned array contains empty strings where spaces
- // were repeated.
- print(line.characters.split(separator: " ", omittingEmptySubsequences: false)
- .map(String.init))
- // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
看看官方文档对这三个参数的解释,懒得翻译了,也不是很难懂。
- /// - Parameters:
- /// - separator: The element that should be split upon.
- /// - maxSplits: The maximum number of times to split the collection, or
- /// one less than the number of subsequences to return. If
- /// `maxSplits + 1` subsequences are returned, the last one is a suffix
- /// of the original collection containing the remaining elements.
- /// `maxSplits` must be greater than or equal to zero. The default value
- /// is `Int.max`.
- /// - omittingEmptySubsequences: If `false`, an empty subsequence is
- /// returned in the result for each consecutive pair of `separator`
- /// elements in the collection and for each instance of `separator` at
- /// the start or end of the collection. If `true`, only nonempty
- /// subsequences are returned. The default value is `true`.
- /// - Returns: An array of subsequences, split from this collection's
- /// elements.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!