切片字符串斯威夫特 [英] Slicing Strings Swift
问题描述
我想将一个很长的字符串从一个单词切成另一个单词.我想获得这些词之间的子字符串.为此,我使用以下字符串扩展名:
I want to slice a very long string from one word to another. I want to get the substring between those words. For that, I use the following string extension:
extension String {
func slice(from: String, to: String) -> String? {
guard let rangeFrom = range(of: from)?.upperBound else { return nil }
guard let rangeTo = self[rangeFrom...].range(of: to)?.lowerBound else { return nil }
return String(self[rangeFrom..<rangeTo])
}
这确实很好,但是我的原始字符串包含一些从"到到"单词,并且我需要这两个单词之间的每个子字符串,但是通过扩展,我只能得到第一个子字符串
That works really good, but my raw-string contains a few of the "from" "to"-words and I need every substring that is between of these two words, but with my extension I can ony get the first substring.
示例:
let raw = "id:244476end36475677id:383848448end334566777788id:55678900end543"
我想从这个原始字符串示例中获取以下子字符串:
I want to get the following substrings from this raw string example:
sub1 = "244476"
sub2 = "383848448"
sub3 = "55678900"
如果我打电话:
var text = raw.slice(from: "id:" , to: "end")
我只会第一次出现(text ="244476")
I only get the first occurence (text = "244476")
感谢您的阅读.每个答案都很好.
Thank you for reading. Every answer would be nice.
PS:通过在stackoverflow中编写代码段,我总是会出错.
PS: I get always an error by making code snippets in stackoverflow.
推荐答案
您可以使用while循环来获取子字符串的范围,以重复从该点到字符串末尾的搜索,并使用map从以下位置获取子字符串结果范围:
You can get the ranges of your substrings using a while loop to repeat the search from that point to the end of your string and use map to get the substrings from the resulting ranges:
extension StringProtocol {
func ranges<S:StringProtocol,T:StringProtocol>(between start: S, and end: T, options: String.CompareOptions = []) -> [Range<Index>] {
var ranges: [Range<Index>] = []
var startIndex = self.startIndex
while startIndex < endIndex,
let lower = self[startIndex...].range(of: start, options: options)?.upperBound,
let range = self[lower...].range(of: end, options: options) {
let upper = range.lowerBound
ranges.append(lower..<upper)
startIndex = range.upperBound
}
return ranges
}
func substrings<S:StringProtocol,T:StringProtocol>(between start: S, and end: T, options: String.CompareOptions = []) -> [SubSequence] {
ranges(between: start, and: end, options: options).map{self[$0]}
}
}
游乐场测试:
Playground testing:
let string = """
your text
id:244476end
id:383848448end
id:55678900end
the end
"""
let substrings = string.substrings(between: "id:", and: "end") // ["244476", "383848448", "55678900"]
这篇关于切片字符串斯威夫特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!