簡體   English   中英

查找從給定索引開始的字符串的第一次出現

[英]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: nillocale: nil可以省略,因為這些參數具有默認值。

  • String擴展方法中,可以將String.Index縮短為Index ,與String.CompareOptions類似。

  • 我不會調用可選參數startIndex因為這會導致與StringstartIndex屬性混淆。

放在一起:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM