我来自Java。我研究了Swift文档并理解了大部分概念。
我现在寻找的是等同于Java indexOf和lastIndexOf方法来查找字符串中子字符串的位置。
我已经找到了一个使用rangeOfString并使用startIndex属性的解决方案。这看起来有助于我定义indexOf方法。
但我认为rangeOfString只从字符串的开头开始搜索。它是否正确?如果是这样,我如何反向搜索(从字符串的结尾到开始)?
我的意思是拥有f.e.字符串“hello world”如果我开始搜索“l”,那么我想在第9位而不是第2位找到该字母。
答案 0 :(得分:23)
在Swift 3中
Java indexOf equivalent:
var index1 = string1.index(string1.endIndex, offsetBy: -4)
Java lastIndexOf等价物:
var index2 = string2.range(of: ".", options: .backwards)?.lowerBound
答案 1 :(得分:6)
extension String {
func indexOf(_ input: String,
options: String.CompareOptions = .literal) -> String.Index? {
return self.range(of: input, options: options)?.lowerBound
}
func lastIndexOf(_ input: String) -> String.Index? {
return indexOf(input, options: .backwards)
}
}
"hello world".indexOf("l") // 2
"hello world".lastIndexOf("l") // 9
答案 2 :(得分:3)
如果希望返回的值为Int:
extension String {
func lastIndex(of string: String) -> Int? {
guard let index = range(of: string, options: .backwards) else { return nil }
return self.distance(from: self.startIndex, to: index.lowerBound)
}
}
答案 3 :(得分:0)
有一个内置的swift函数,用于查找字符的最后一次出现的索引。功能签名在
下public func lastIndex(of element: Character) -> String.Index?{}
我们可以获取如下字符的索引:
let url = "http://www.google.com/abc"
guard let lastIndexOfChar = url.lastIndex(of: "/") else { return nil }
let startIndex = url.index(lastIndexOfChar, offsetBy:1)
let substring = url[startIndex..<url.endIndex] // prints "abc"