是否有任何现有函数在另一个字符串中查找子字符串的索引?像.indexOfSubstring
这样的方法感谢:
let word: String = "Hey there, how are you?"
let indexOf: Int = word.indexOfSubstring("ere, how are")
println("index = " + \(indexOf))
并打印:
index = 6
答案 0 :(得分:2)
您可以使用rangeOfString
方法:
import Foundation
let word: String = "Hey there, how are you?"
if let range = word.rangeOfString("ere, how are") {
let index = distance(word.startIndex, range.startIndex)
println("index = \(index)")
}
它返回一个范围,即搜索到的字符串的两边 - 只使用startIndex
属性。
请注意,这是从NSString
答案 1 :(得分:1)
Swift中没有构建方法。您需要自己实现它。另一个实现是
/// Get the start index of string
///
/// :return start index of .None if not found
public func indexOf(str: String) -> Int? {
return self.indexOfRegex(Regex.escapeStr(str))
}
/// Get the start index of regex pattern
///
/// :return start index of .None if not found
public func indexOfRegex(pattern: String) -> Int? {
if let range = Regex(pattern).rangeOfFirstMatch(self).toRange() {
return range.startIndex
}
return .None
}
此代码来自此库,其中包含一些常见swift类型的扩展,例如String https://github.com/ankurp/Dollar.swift/blob/master/Cent/Cent/String.swift#L62
您可以查看有关使用情况的文档 http://www.dollarswift.org/#indexof-str-string-int