【发布时间】:2019-07-19 12:57:25
【问题描述】:
通过 Swift 算法,包括蛮力字符串搜索,即:https://github.com/raywenderlich/swift-algorithm-club/tree/master/Brute-Force%20String%20Search
据说输出是7
现在实际上输出是 (String.Index?) - 虽然我可以用它下标,但我想实际看到值 - 7。
代码是
extension String {
func indexOf(_ pattern: String) -> String.Index? {
for i in self.characters.indices {
var j = i
var found = true
for p in pattern.characters.indices{
if j == self.characters.endIndex || self[j] != pattern[p] {
found = false
break
} else {
j = self.characters.index(after: j)
}
}
if found {
return i
}
}
return nil
}
}
我在文档和此处查看了将 String.Index 转换为范围:Convert String.Index to Int or Range<String.Index> to NSRange 但该问题的答案是旧的,并且没有为 Swift 4 提供答案(如果存在这样的答案)。
到的距离也不起作用:
let s = "Hello, World"
let res = ( s.indexOf("World") )
let index: Int = s.startIndex.distance(to: res)
print (s[res!])
现有的 OffsetIndexableCollection 甚至无法编译
那么我该如何转换
s.indexOf("World")
到“7”,其中 s 是“Hello, World”
【问题讨论】:
-
它不是重复的,我什至链接到建议它不是重复的问题之一,因为它没有回答问题中详细解释的问题。下面的答案确实回答了这个问题,并且没有出现在所谓的重复中!为什么人们在这样做之前不阅读问题?
-
关于你的代码试图获取距离
let s = "Hello, World" if let res = s.indexOf("World") { let distance = s.distance(from: s.startIndex, to: res) print(s[res...]) // "World\n" print(distance) // 7 }
标签: swift