需求:從一串字符串中查找子字符串的位置
實現:系統框架中並沒有可以直接調用的方法直接獲取子字符串開始的位置,需要以下幾步即可獲取到子字符串的起始位置。
應用場景:比如我們要對 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