繁体   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