實例方法
split(max
split(maxSplits:omittingEmptySubsequences:whereSeparator:)
按順序返回集合的最長可能子序列,這些子序列不包含滿足給定謂詞的元素。
聲明
func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
whereSeparator isSeparator: (Self.Element) throws -> Bool
) rethrows -> [Self.SubSequence]
返回值
一個子序列數組,從這個集合的元素中分離出來。
參數
maxSplits
拆分集合的最大次數,或者比要返回的子序列數少一。如果返回
maxSplits + 1
子序列,則最後一個是包含剩餘元素的原始集合的後綴。maxSplits
必須大於或等於零。默認值為Int.max
。omittingEmptySubsequences
如果
false
,則對於滿足isSeparator
謂詞的每對連續元素以及滿足isSeparator
謂詞的集合開頭或結尾的每個元素,結果中都會返回一個空子序列。默認值為true
。isSeparator
一個閉包,它接受一個元素作為參數並返回一個布爾值,指示是否應該在該元素處拆分集合。
詳述
結果數組最多包含maxSplits + 1
子序列。用於拆分序列的元素不會作為任何子序列的一部分返回。
以下示例顯示了使用匹配空格的閉包拆分字符串時 maxSplits
和 omittingEmptySubsequences
參數的效果。 split
的第一次使用返回最初由一個或多個空格分隔的每個單詞。
let line = "BLANCHE: I don't want realism. I want magic!"
print(line.split(whereSeparator: { $0 == " " }))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
第二個示例將1
傳遞給maxSplits
參數,因此原始字符串隻被拆分一次,分成兩個新字符串。
print(line.split(maxSplits: 1, whereSeparator: { $0 == " " }))
// Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
最後一個示例為omittingEmptySubsequences
參數傳遞false
,因此返回的數組包含重複空格的空字符串。
print(line.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " }))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相關用法
- Swift String.UnicodeScalarView split(separator:maxSplits:omittingEmptySubsequences:)用法及代碼示例
- Swift String.UnicodeScalarView sorted()用法及代碼示例
- Swift String.UnicodeScalarView shuffled(using:)用法及代碼示例
- Swift String.UnicodeScalarView starts(with:)用法及代碼示例
- Swift String.UnicodeScalarView shuffled()用法及代碼示例
- Swift String.UnicodeScalarView subscript(_:)用法及代碼示例
- Swift String.UnicodeScalarView suffix(_:)用法及代碼示例
- Swift String.UnicodeScalarView sorted(by:)用法及代碼示例
- Swift String.UnicodeScalarView suffix(from:)用法及代碼示例
- Swift String.UnicodeScalarView flatMap(_:)用法及代碼示例
- Swift String.UnicodeScalarView min(by:)用法及代碼示例
- Swift String.UnicodeScalarView lastIndex(of:)用法及代碼示例
- Swift String.UnicodeScalarView filter(_:)用法及代碼示例
- Swift String.UnicodeScalarView replaceSubrange(_:with:)用法及代碼示例
- Swift String.UnicodeScalarView compactMap(_:)用法及代碼示例
- Swift String.UnicodeScalarView removeFirst(_:)用法及代碼示例
- Swift String.UnicodeScalarView elementsEqual(_:)用法及代碼示例
- Swift String.UnicodeScalarView remove(at:)用法及代碼示例
- Swift String.UnicodeScalarView lexicographicallyPrecedes(_:)用法及代碼示例
- Swift String.UnicodeScalarView append(_:)用法及代碼示例
- Swift String.UnicodeScalarView contains(_:)用法及代碼示例
- Swift String.UnicodeScalarView enumerated()用法及代碼示例
- Swift String.UnicodeScalarView insert(_:at:)用法及代碼示例
- Swift String.UnicodeScalarView last用法及代碼示例
- Swift String.UnicodeScalarView reversed()用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 String.UnicodeScalarView split(maxSplits:omittingEmptySubsequences:whereSeparator:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。