takes a series of strings and indexes them in a body of text.
struct WordMap {
let string:String
var indexes:[String:[Int]]
let substrs:[String]
let substrset:Set<String>
init(string:String, substrs:[String]){
self.string = string
self.substrs = substrs
self.indexes = [String:[Int]]()
let chars = Array(string.characters)
//easy to access set of substrs you want to map
self.substrset = Set<String>(substrs)
let length = self.string.characters.count
//initialize index map
for elem in self.substrs {
self.indexes[elem] = [Int]()
}
//repeating loop to get substr indexes
for phrase in self.substrs {
var substart = 0
var subend = phrase.characters.count-1
//intermediate loop to cut substrs of specific sizes
while subend < length {
let slice = String(chars[substart...subend])
if slice == phrase {
self.indexes[slice]!.append(substart)
}
substart += 1
subend += 1
}
}
}
//gets the indexes at which a word appears in a body of text
func getIndexes(string:String) -> [Int] {
return self.indexes[string]!
}
}
let test = WordMap(string:"hello fine sire how are you today? we missed you", substrs: ["you", "sir"])
test.indexes
//["you": [24, 45], "sir": [11]]