swift 3 get start index (as int) of substring

前端 未结 2 1852
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 15:24

I would like to get the start and end position of a substring within a string. Example: in the string \"hi this is my name\"; if I provide the string \"this\" I would like t

相关标签:
2条回答
  • 2021-01-01 15:56

    The distance(from:to:) method of String computes the difference between two String.Index values:

    let mystring = "hi this is my name"
    if let range = mystring.range(of: "this") {
        let startPos = mystring.distance(from: mystring.startIndex, to: range.lowerBound)
        let endPos = mystring.distance(from: mystring.startIndex, to: range.upperBound)
        print(startPos, endPos) // 3 7
    }
    

    Actually it just forwards the call to the string's CharacterView, so the above gives the same result as

    let mystring = "hi this is my name"
    if let range = mystring.range(of: "this") {
        let startPos = mystring.characters.distance(from: mystring.characters.startIndex, to: range.lowerBound)
        let endPos = mystring.characters.distance(from: mystring.characters.startIndex, to: range.upperBound)
        print(startPos, endPos) // 3 7
    }
    

    If you need all occurrences of the string:

    let mystring = "this is this and that is that"
    var searchPosition = mystring.startIndex
    while let range = mystring.range(of: "this", range: searchPosition..<mystring.endIndex) {
        let startPos = mystring.distance(from: mystring.startIndex, to: range.lowerBound)
        let endPos = mystring.distance(from: mystring.startIndex, to: range.upperBound)
        print(startPos, endPos)
    
        searchPosition = range.upperBound
    }
    
    0 讨论(0)
  • Adapted answer from Martin R into a function gives you the first occurrence as an NSRange. You could turn this into an extension of String also.

    public class func indexOf(string: String, substring: String) -> NSRange? {
        if let range = string.range(of: substring) {
            let startPos = string.distance(from: string.startIndex, to: range.lowerBound)
            return NSMakeRange(startPos, substring.count)
        }
    }
    
    0 讨论(0)
提交回复
热议问题