Swift3.0 split函数切割字符串

本文详细介绍了Swift语言中字符串分割函数的使用方法,包括如何指定分隔符、最大分割次数及是否忽略空子串等参数,并通过实例展示了这些参数的具体应用。

我们先看函数的原型:

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


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

[objc] view plain copy
  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的话就把原来的字符串切成两个。

 

[objc] view plain copy
  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!"]"  

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

 

[objc] view plain copy
  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!"]"  


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

 

[objc] view plain copy
    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. 

转载于:https://www.cnblogs.com/Free-Thinker/p/7338223.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值