Find all indices of a search term in a string

后端 未结 3 1034
予麋鹿
予麋鹿 2021-01-19 10:08

I need a fast method to find all indices of a search term that might occur in a string. I tried this \'brute force\' String extension method:

//         


        
3条回答
  •  [愿得一人]
    2021-01-19 11:01

    Using NSRegularExpression in Swift 4, you can do it like this. NSRegularExpression has been around forever and is probably a better choice than rolling your own algorithm for most cases.

    let text = "The quieter you become, the more you can hear."
    let searchTerm = "you"
    
    let regex = try! NSRegularExpression(pattern: searchTerm, options: [])
    let range: NSRange = NSRange(text.startIndex ..< text.endIndex, in: text)
    let matches: [NSTextCheckingResult] = regex.matches(in: text, options: [], range: range)
    let ranges: [NSRange] = matches.map { $0.range }
    let indices: [Int] = ranges.map { $0.location }
    let swiftRanges = ranges.map { Range($0, in: text) }
    let swiftIndices: [String.Index] = swiftRanges.flatMap { $0?.lowerBound }
    

提交回复
热议问题