在Swift中拆分字符串而不删除定界符

在Swift中拆分字符串而不删除定界符,第1张

在Swift中拆分字符串而不删除定界符

此方法适用于

CollectionTypes
,而不是
String
s,但是它应该很容易适应:

extension CollectionType {  func splitAt(@noescape isSplit: Generator.Element throws -> Bool) rethrows ->  [SubSequence] {    var p = startIndex    return try indices      .filter { i in try isSplit(self[i]) }      .map { i in        defer { p = i }        return self[p..<i]      } + [suffixFrom(p)]  }}extension CollectionType where Generator.Element : Equatable {  func splitAt(splitter: Generator.Element) -> [SubSequence] {    return splitAt { el in el == splitter }  }}

您可以这样使用它:

let sentence = "Hello, my name is oisdk. This should split: but only at punctuation!"let puncSet = Set("!.,:".characters)sentence  .characters  .splitAt(puncSet.contains)  .map(String.init)// ["Hello", ", my name is oisdk", ". This should split", ": but only at punctuation", "!"]

或者,此版本使用for循环,并 定界符 拆分:

extension CollectionType {  func splitAt(@noescape isSplit: Generator.Element throws -> Bool) rethrows ->  [SubSequence] {    var p = startIndex    var result: [SubSequence] = []    for i in indices where try isSplit(self[i]) {      result.append(self[p...i])      p = i.successor()    }    if p != endIndex { result.append(suffixFrom(p)) }    return result  }}extension CollectionType where Generator.Element : Equatable {  func splitAt(splitter: Generator.Element) -> [SubSequence] {    return splitAt { el in el == splitter }  }}let sentence = "Hello, my name is oisdk. This should split: but only at punctuation!"let puncSet = Set("!.,:".characters)sentence  .characters  .splitAt(puncSet.contains)  .map(String.init)// ["Hello,", " my name is oisdk.", " This should split:", " but only at punctuation!"]

或者,如果你想获得最斯威夫特功能为一体的功能(

defer
throws
,一个协议扩展,一个邪恶的
flatMap
guard
以及选配):

extension CollectionType {  func splitAt(@noescape isSplit: Generator.Element throws -> Bool) rethrows -> [SubSequence] {    var p = startIndex    var result: [SubSequence] = try indices.flatMap { i in      guard try isSplit(self[i]) else { return nil }      defer { p = i.successor() }      return self[p...i]    }    if p != endIndex { result.append(suffixFrom(p)) }    return result  }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4927758.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存