【问题标题】:Explanation of lastIndex of: and firstIndex of: used in a string in SwiftSwift中字符串中lastIndex of:和firstIndex of:的解释
【发布时间】:2019-09-20 10:23:21
【问题描述】:

我正在用 Swift 解决一个编程问题,我在网上找到了一个我不完全理解的解决方案,问题是:编写一个函数来反转输入字符串中(可能是嵌套的)括号中的字符。解决办法是

var inputString = "foo(bar)baz(ga)kjh"

    var s = inputString
    while let openIdx = s.lastIndex(of: "(") {
        let closeIdx = s[openIdx...].firstIndex(of:")")!
        s.replaceSubrange(openIdx...closeIdx, with: s[s.index(after: openIdx)..<closeIdx].reversed())
    }

print (s) // output: foorabbazagkjh (the letters inside the braces are reversed) 

我想详细了解:lastIndex(of: 在这种情况下 以及let closeIdx = s[openIdx...].firstIndex(of:")")! 的作用

【问题讨论】:

标签: swift xcode lastindexof


【解决方案1】:

尝试这类问题的最佳地点是Playground。另外,请查看documentation

现在让我们来看看每一个语句:

let openIdx = s.lastIndex(of: "(") // it will find the last index of "(", the return type here is Array.Index?

所以如果我在包含直到字符串结尾的索引之后打印值,它将是

print(s[openIdx!...]) // `!` exclamation is used for forced casting
// (ga)kjh

现在回答你的第二个问题;

let closeIdx = s[openIdx...].firstIndex(of:")")!

s[openIdx...]在第一次迭代中等于(ga)kjh,所以它会在a之后返回)的索引。

建议总是打破陈述并了解每个表达式在做什么。

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 2013-10-21
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 2021-11-10
    • 2012-05-15
    相关资源
    最近更新 更多