iOS - Swift 实现字符串查找子字符串的位置

需求:从一串字符串中查找子字符串的位置

实现:系统框架中并没有可以直接调用的方法直接获取子字符串开始的位置,需要以下几步即可获取到子字符串的起始位置。

应用场景:比如我们要对 UILabel 的文本中的部分字符标记,那么我们就需要找出来要标记的文本的位置,结合文本的长度,我们就可以实现标记

第一步:我们需要借助下面的这个方法来获取位置

参数是两个索引,如果要获取子字符串的起始位置,只需要传递父字符串的开始索引和子字符串在父字符串中的开始索引。第一个参数就是 str.startIndex,第二个参数需要第二步中的方法获取到

    /// Returns the distance between two indices.
    ///
    /// - Parameters:
    ///   - start: A valid index of the collection.
    ///   - end: Another valid index of the collection. If `end` is equal to
    ///     `start`, the result is zero.
    /// - Returns: The distance between `start` and `end`.
    ///
    /// - Complexity: O(*n*), where *n* is the resulting distance.
    @inlinable public func distance(from start: String.Index, to end: String.Index) -> String.IndexDistance

第二步:获取子字符串在父字符串中的范围 (Rang: 是一个半开放的区间,不包含最大值)。

获取到 Range 后,需要把得到的 Rang.lowerBound 传递到第一步方法中的第二个参数中,我们就获取到了子字符串在父字符串中的位置。

str.range(of:)

示例:

let helloWorld: String = "Hello World"
let wo: String = "Wo"
let range: Range = helloWorld.range(of: wo)!
let location = helloWorld.distance(from: helloWorld.startIndex, to: range.lowerBound)
// location: 6

最后我们可以得到 location 的值为 6

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章