迅速查找所有出现的子串 [英] Swift find all occurrences of a substring

查看:65
本文介绍了迅速查找所有出现的子串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Swift中有一个String类的扩展,它返回给定子字符串的第一个字母的索引.

I have an extension here of the String class in Swift that returns the index of the first letter of a given substring.

任何人都可以帮助我做到这一点,这样它将返回所有出现的数组,而不仅仅是第一个出现的数组?

Can anybody please help me make it so it will return an array of all occurrences instead of just the first one?

谢谢.

extension String {
    func indexOf(string : String) -> Int {
        var index = -1
        if let range = self.range(of : string) {
            if !range.isEmpty {
                index = distance(from : self.startIndex, to : range.lowerBound)
            }
        }
        return index
    }
}

例如,我想要的不是50的返回值,而是[50, 74, 91, 103]

For example instead of a return value of 50 I would like something like [50, 74, 91, 103]

推荐答案

您只需不断扩大搜索范围,直到找不到子字符串的更多实例为止:

You just keep advancing the search range until you can't find any more instances of the substring:

extension String {
    func indicesOf(string: String) -> [Int] {
        var indices = [Int]()
        var searchStartIndex = self.startIndex

        while searchStartIndex < self.endIndex,
            let range = self.range(of: string, range: searchStartIndex..<self.endIndex),
            !range.isEmpty
        {
            let index = distance(from: self.startIndex, to: range.lowerBound)
            indices.append(index)
            searchStartIndex = range.upperBound
        }

        return indices
    }
}

let keyword = "a"
let html = "aaaa"
let indicies = html.indicesOf(string: keyword)
print(indicies) // [0, 1, 2, 3]

这篇关于迅速查找所有出现的子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆