0
指定されたインデックスから始まる文字列の最初の出現を探したい。 this answerに基づいて指定されたインデックスから始まる文字列の最初の出現を見つけよう
私は次の関数を作成しました:
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
}
}
残念ながら、インデックスの一部が動作しません。次のコード例
は3
の代わりにnil
を返します。
let str = "test"
str.index(of: "t", from: str.index(str.startIndex, offsetBy: 1))
あなたは間違った範囲に検索を制限しています。 'string.endIndex'は' self.endIndex'(または単に 'endIndex')でなければなりません。 –
いつものように、あなたは正しい@MartinRです。今、それは動作します、ありがとう! – Daniel