2020年12月21日星期一

Swift: String firstIndex after character

I'm trying to detect the parentheses on string for example: foo(bar)baz(blim) to and reverse the content inside of the parentheses but I'm getting out of bounce range on my implementation:

    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      }    

how can I get the tmpStr.firstIndex(of: ")") after the startIndex any of you knows how can do that?

I'll really appreciate your help

https://stackoverflow.com/questions/65402215/swift-string-firstindex-after-character December 22, 2020 at 09:38AM

没有评论:

发表评论