[英]find first occurrence of string starting at given index
我想找到從給定索引開始的字符串的第一次出現。
基於此答案,我創建了以下功能:
func index(of string: String, from startIndex: String.Index? = nil, options: String.CompareOptions = .literal) -> String.Index? {
if let startIndex = startIndex {
return range(of: string, options: options, range: startIndex ..< string.endIndex, locale: nil)?.lowerBound
} else {
return range(of: string, options: options, range: nil, locale: nil)?.lowerBound
}
}
不幸的是,帶有索引的部分不起作用。
例如,以下代碼返回nil
而不是3
:
let str = "test"
str.index(of: "t", from: str.index(str.startIndex, offsetBy: 1))
您將搜索限制在錯誤的范圍內。 string.endIndex
應該是self.endIndex
(或者只是endIndex
)。
進一步說明:
range: nil
和locale: nil
可以省略,因為這些參數具有默認值。
在String
擴展方法中,可以將String.Index
縮短為Index
,與String.CompareOptions
類似。
我不會調用可選參數startIndex
因為這會導致與String
的startIndex
屬性混淆。
放在一起:
extension String {
func index(of string: String, from startPos: Index? = nil, options: CompareOptions = .literal) -> Index? {
if let startPos = startPos {
return range(of: string, options: options, range: startPos ..< endIndex)?.lowerBound
} else {
return range(of: string, options: options)?.lowerBound
}
}
}
或者
extension String {
func index(of string: String, from startPos: Index? = nil, options: CompareOptions = .literal) -> Index? {
let startPos = startPos ?? startIndex
return range(of: string, options: options, range: startPos ..< endIndex)?.lowerBound
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.