Find all indices of a search term in a string

后端 未结 3 1061
予麋鹿
予麋鹿 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:02

    Instead of checking for the search term at each position of the string you could use rangeOfString() to find the next occurrence (hoping that rangeOfString() uses more advanced algorithms):

    extension String {
    
        func indicesOf(searchTerm:String) -> [Int] {
            var indices = [Int]()
            var pos = self.startIndex
            while let range = self.rangeOfString(searchTerm, range: pos ..< self.endIndex) {
                indices.append(distance(self.startIndex, range.startIndex))
                pos = range.startIndex.successor()
            }
            return indices
        }
    }
    

    Generally, it depends on the size of the input string and the size of the search string which algorithm is "the fastest". You'll find an overview with links to various algorithms in String searching algorithm.

    Update for Swift 3:

    extension String {
    
        func indices(of searchTerm:String) -> [Int] {
            var indices = [Int]()
            var pos = self.startIndex
            while let range = range(of: searchTerm, range: pos ..< self.endIndex) {
                indices.append(distance(from: startIndex, to: range.lowerBound))
                pos = index(after: range.lowerBound)
            }
            return indices
        }
    }
    

提交回复
热议问题