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.","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:","","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.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...