加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift3.0 split函数切割字符串

发布时间:2020-12-14 06:22:23 所属栏目:百科 来源:网络整理
导读:我们先看函数的原型: public func split(separator: Self.Iterator.Element,maxSplits: Int = default,omittingEmptySubsequences: Bool = default) - [Self.SubSequence] 第一个参数就不用解释了,传入要切割的字符串,像这样 let line = "BLANCHE: I don'

我们先看函数的原型:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读