Swift3.0 split函数切割字符串

我们先看函数的原型:

  1. public func split(separator: Self.Iterator.Element, maxSplits: Int = default, omittingEmptySubsequences: Bool = default) -> [Self.SubSequence]  


第一个参数就不用解释了,传入要切割的字符串,像这样

  1. let line = "BLANCHE:   I don't want realism. I want magic!"  
  2. print(line.characters.split(separator: " ")  
  3.                      .map(String.init))  
  4. // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"  


下面看第二个参数,像这样,意思是切割几次,设置为1的话就把原来的字符串切成两个。

 

  1. // The second example passes `1` for the `maxSplits` parameter, so the  
  2. // original string is split just once, into two new strings.  
  3.   
  4. print(line.characters.split(separator: " ", maxSplits: 1)  
  5.                      .map(String.init))  
  6. // Prints "["BLANCHE:", "  I don\'t want realism. I want magic!"]"  

第三个参数就很明确了,是否保留隐藏字符

 

  1. // The final example passes `false` for the `omittingEmptySubsequences`  
  2. // parameter, so the returned array contains empty strings where spaces  
  3. // were repeated.  
  4.   
  5. print(line.characters.split(separator: " ", omittingEmptySubsequences: false)  
  6.                       .map(String.init))  
  7. // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"  


看看官方文档对这三个参数的解释,懒得翻译了,也不是很难懂。

 

    1. /// - Parameters:  
    2. ///   - separator: The element that should be split upon.  
    3. ///   - maxSplits: The maximum number of times to split the collection, or  
    4. ///     one less than the number of subsequences to return. If  
    5. ///     `maxSplits + 1` subsequences are returned, the last one is a suffix  
    6. ///     of the original collection containing the remaining elements.  
    7. ///     `maxSplits` must be greater than or equal to zero. The default value  
    8. ///     is `Int.max`.  
    9. ///   - omittingEmptySubsequences: If `false`, an empty subsequence is  
    10. ///     returned in the result for each consecutive pair of `separator`  
    11. ///     elements in the collection and for each instance of `separator` at  
    12. ///     the start or end of the collection. If `true`, only nonempty  
    13. ///     subsequences are returned. The default value is `true`.  
    14. /// - Returns: An array of subsequences, split from this collection's  
    15. ///   elements. 
posted @   brave-sailor  阅读(476)  评论(0编辑  收藏  举报
编辑推荐:
· 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代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示