gpt4 book ai didi

swift - 如何检测多行字符串中每一行的第一个索引?

转载 作者:搜寻专家 更新时间:2023-11-01 06:59:31 24 4
gpt4 key购买 nike

我有一个包含多行的 string,每行用不同的分隔符分隔,如 \r\n\n 等。所以我使用 CharacterSet.newlines 来检测行。但我也想要每个句子的第一个索引。我怎样才能做到这一点?

我使用下面的代码来分隔行:

for (i, mySentence) in sampleString.components(separatedBy: CharacterSet.newlines).enumerated() {
...
}

最佳答案

为此,我将“手动”搜索换行符,以便当前子串及其位置均可用:

let sampleString = "aaa\naaa\r\nbbb\rccc"

var lines = [String]()
var positions = [String.Index]()

var pos = sampleString.startIndex // Current position
while let r = sampleString[pos...].rangeOfCharacter(from: .newlines) {
if pos != r.lowerBound {
lines.append(String(sampleString[pos..<r.lowerBound]))
positions.append(pos)
}
pos = r.upperBound // Continue _after_ the newline character
}
// The final component:
if pos != sampleString.endIndex {
lines.append(String(sampleString[pos...]))
positions.append(pos)
}

关于swift - 如何检测多行字符串中每一行的第一个索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51492612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com