【问题标题】:Understanding the removeRange(_:) documentation了解 removeRange(_:) 文档
【发布时间】:2015-05-03 18:53:31
【问题描述】:

要删除指定范围内的子字符串,请使用 removeRange(_:) 方法:

1 let range = advance(welcome.endIndex, -6)..<welcome.endIndex
2 welcome.removeRange(range)
3 println(welcome)
4 // prints "hello"

摘自:Apple Inc. “Swift 编程语言”。电子书。 https://itun.es/ca/jEUH0.l

你好,

我没有完全理解上面代码中第 1 行的语法和功能。

请用这个字符串解释一下:

let welcome = "hello there"

这是我的工作:

“要更改开始和结束索引,请使用advance()。”
来自:https://stackoverflow.com/a/24045156/4839671

欢迎提供更好的 advance() 文档。即它的论点

使用..&lt; 创建一个省略其上限值的范围

摘自:Apple Inc. “Swift 编程语言”。电子书。 https://itun.es/ca/jEUH0.l

welcome.endIndex 将是 11

【问题讨论】:

  • 有什么难度?字符串有 startIndex 和 endIndex。您必须通过提前增加/减少它们。范围类似于 &lt;index&gt;...&lt;index&gt;index..<index>.
  • 我不知道变量(或常量)可以保持范围。

标签: swift


【解决方案1】:

斯威夫特 2

我们将使用var,因为removeRange 需要对可变字符串进行操作。

var welcome = "hello there"

这一行:

let range = welcome.endIndex.advancedBy(-6)..<welcome.endIndex

表示我们从字符串的末尾(welcome.endIndex)开始,向后移动 6 个字符(前移一个负数 = 向后移动),然后询问我们的位置和当前位置之间的范围(..&lt;)字符串结尾 (welcome.endIndex)。

它创建了一个5..&lt;11的范围,它包含了字符串的"there"部分。

如果您从字符串中删除此字符范围

welcome.removeRange(range)

那么你的字符串将是剩下的部分:

print(welcome) // prints "hello"

你可以换一种方式(从字符串的起始索引开始)以获得相同的结果:

welcome = "hello there"
let otherRange = welcome.startIndex.advancedBy(5)..<welcome.endIndex
welcome.removeRange(otherRange)
print(welcome) // prints "hello"

这里我们从字符串的开头 (welcome.startIndex) 开始,然后我们前进 5 个字符,然后我们从这里到字符串的结尾 (welcome.endIndex) 创建一个范围 (..&lt;)。

注意:advance 函数可以向前和向后工作。

斯威夫特 3

语法变了,但概念是一样的。

var welcome = "hello there"
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
print(welcome) // prints "hello"

welcome = "hello there"
let otherRange = welcome.index(welcome.startIndex, offsetBy: 5)..<welcome.endIndex
welcome.removeSubrange(otherRange)
print(welcome) // prints "hello"

【讨论】:

    猜你喜欢
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多