我在Swift中有一个String类的扩展,它返回给定子字符串的第一个字母的索引。
任何人都可以帮我制作它,这样它会返回所有出现的数组,而不仅仅是第一个吗?
谢谢。
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]
的返回值
答案 0 :(得分:17)
您只需继续推进搜索范围,直到找不到子字符串的更多实例:
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]
答案 1 :(得分:4)
这不是真正的内置函数,但我们可以实现修改后的Knuth-Morris-Pratt algorithm来获取我们想要匹配的字符串的所有索引。它也应该非常高效,因为我们不需要在字符串上重复调用范围。
extension String {
func indicesOf(string: String) -> [Int] {
// Converting to an array of utf8 characters makes indicing and comparing a lot easier
let search = self.utf8.map { $0 }
let word = string.utf8.map { $0 }
var indices = [Int]()
// m - the beginning of the current match in the search string
// i - the position of the current character in the string we're trying to match
var m = 0, i = 0
while m + i < search.count {
if word[i] == search[m+i] {
if i == word.count - 1 {
indices.append(m)
m += i + 1
i = 0
} else {
i += 1
}
} else {
m += 1
i = 0
}
}
return indices
}
}
答案 2 :(得分:3)
这是2个功能。一个返回[Range<String.Index>]
,另一个返回[Range<Int>]
。如果您不需要前者,可以将其设为私有。我将其设计为模仿range(of:options:range:locale:)
方法,因此它支持所有相同的功能。
import Foundation
let s = "abc abc abc abc abc"
extension String {
func allRanges(of aString: String,
options: String.CompareOptions = [],
range: Range<String.Index>? = nil,
locale: Locale? = nil) -> [Range<String.Index>] {
//the slice within which to search
let slice = (range == nil) ? self : self[range!]
var previousEnd: String.Index? = s.startIndex
var ranges = [Range<String.Index>]()
while let r = slice.range(of: aString, options: options,
range: previousEnd! ..< s.endIndex,
locale: locale) {
if previousEnd != self.endIndex { //don't increment past the end
previousEnd = self.index(after: r.lowerBound)
}
ranges.append(r)
}
return ranges
}
func allRanges(of aString: String,
options: String.CompareOptions = [],
range: Range<String.Index>? = nil,
locale: Locale? = nil) -> [Range<Int>] {
return allRanges(of: aString, options: options, range: range, locale: locale)
.map(indexRangeToIntRange)
}
func indexToInt(_ index: String.Index) -> Int {
return self.distance(from: self.startIndex, to: index)
}
func indexRangeToIntRange(_ range: Range<String.Index>) -> Range<Int> {
return indexToInt(range.lowerBound) ..< indexToInt(range.upperBound)
}
}
print(s.allRanges(of: "abc") as [Range<String.Index>])
print(s.allRanges(of: "abc") as [Range<Int>])
如果你只想要每个的起始指数,只需点击.map{ $0.lowerBound }
答案 3 :(得分:2)
我知道我们不是在这里玩高尔夫代码,但对于那些对使用var
或循环的函数式单行实现感兴趣的人来说,这是另一种可能的解决方案:
extension String {
func indices(of string: String) -> [Int] {
return indices.reduce([]) { $1.encodedOffset > ($0.last ?? -1) && self[$1...].hasPrefix(string) ? $0 + [$1.encodedOffset] : $0 }
}
}
答案 4 :(得分:0)
这可以通过递归方法完成。我用数字字符串来测试它。它返回一个Int
的可选数组,这意味着如果找不到子字符串它将为nil。
extension String {
func indexes(of string: String, offset: Int = 0) -> [Int]? {
if let range = self.range(of : string) {
if !range.isEmpty {
let index = distance(from : self.startIndex, to : range.lowerBound) + offset
var result = [index]
let substr = self.substring(from: range.upperBound)
if let substrIndexes = substr.indexes(of: string, offset: index + distance(from: range.lowerBound, to: range.upperBound)) {
result.append(contentsOf: substrIndexes)
}
return result
}
}
return nil
}
}
let numericString = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"
numericString.indexes(of: "3456")
答案 5 :(得分:0)
我已经调整了接受的答案,以便可以配置case sensitivity
extension String {
func allIndexes(of subString: String, caseSensitive: Bool = true) -> [Int] {
let subString = caseSensitive ? subString : subString.lowercased()
let mainString = caseSensitive ? self : self.lowercased()
var indices = [Int]()
var searchStartIndex = mainString.startIndex
while searchStartIndex < mainString.endIndex,
let range = mainString.range(of: subString, range: searchStartIndex..<mainString.endIndex),
!range.isEmpty
{
let index = distance(from: mainString.startIndex, to: range.lowerBound)
indices.append(index)
searchStartIndex = range.upperBound
}
return indices
}
}
答案 6 :(得分:0)
请检查以下答案以在多个位置查找多个项目
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
}
func attributedStringWithColor(_ strings: [String], color: UIColor, characterSpacing: UInt? = nil) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: self)
for string in strings {
let indexes = self.indicesOf(string: string)
for index in indexes {
let range = NSRange(location: index, length: string.count)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
}
}
guard let characterSpacing = characterSpacing else {return attributedString}
attributedString.addAttribute(NSAttributedString.Key.kern, value: characterSpacing, range: NSRange(location: 0, length: attributedString.length))
return attributedString
}
可以如下使用:
let message = "Item 1 + Item 2 + Item 3"
message.attributedStringWithColor(["Item", "+"], color: UIColor.red)