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 @ 2017-08-10 11:15  brave-sailor  阅读(484)  评论(0)    收藏  举报