Swift 查找所有出现的子字符串 [英] Swift find all occurrences of a substring
本文介绍了Swift 查找所有出现的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里有一个 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]
这篇关于Swift 查找所有出现的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文