gpt4 book ai didi

ios - Swift:字符后的字符串firstIndex

转载 作者:行者123 更新时间:2023-12-04 08:23:01 26 4
gpt4 key购买 nike

我正在尝试检测字符串上的括号,例如: foo(bar)baz(blim) 并反转括号内的内容,但我超出了反弹范围我的实现:

func reverseInParentheses(inputString: String) -> String {
var tmpStr = inputString
var done = false
while !done {
if let lastIndexOfChar = tmpStr.lastIndex(of: "(") {
let startIndex = tmpStr.index(lastIndexOfChar, offsetBy:1)
if let index = tmpStr.firstIndex(of: ")") {
let range = startIndex..<index
let strToVerse = String(tmpStr[range])
let reversedStr = reverseStr(str: strToVerse)
tmpStr = tmpStr.replacingOccurrences(of: "(" + strToVerse + ")", with: reversedStr)

}
} else {
done = true
}
}
return tmpStr
}

如何在 startIndex 之后获取 tmpStr.firstIndex(of: ")") 你们知道如何做到这一点吗?

最佳答案

how can I get the tmpStr.firstIndex(of: ")") after the startIndex?

一种方法是在 startIndex 处“剪切”字符串,并获取后半部分。然后在子字符串上使用 firstIndex(of:) 。由于 Substring 只是从中剪切它们的原始字符串的“ View ”,因此 firstIndexOf 仍然返回原始字符串的索引。

let string = "foo(bar)baz(blim)"
if let lastIndexOfChar = string.lastIndex(of: "(") {
let startIndex = string.index(after: lastIndexOfChar)
let substring = string[startIndex..<string.endIndex] // cut off the first part of the string.
// now you have a "Substring" object
if let indexAfterOpenBracket = substring.firstIndex(of: ")") {
// prints "blim", showing that the index is indeed from the original string
print(string[startIndex..<indexAfterOpenBracket])
}
}

您可以将其编写为扩展:

extension StringProtocol {
func firstIndex(of char: Character, after index: Index) -> Index? {
let substring = self[index..<endIndex]
return substring.firstIndex(of: char)
}
}

现在,如果您在 reverseInParentheses 中调用 tmpStr.firstIndex(of: ")", after: startIndex),它应该可以工作。

关于ios - Swift:字符后的字符串firstIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65402215/

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