我有一个文本被分成字符串数组,用户可以点击每个单词,将单词的索引(键)和字符串(值)添加到字典中。
现在,如果用户添加两个或多个相邻的单词,我希望将字符串连接起来,并使它们共享一个索引。
我的想法是使用计算属性,根据字典中的键和值重新排列字符串数组。因此,当用户点击一个单词时,该函数应该更新字典,同时检查是否有相邻的索引已经添加。
示例代码:
let text = "This is a test for merging adjacent words that the user has selected."
//The text divided in separate words that can be tapped
var arrayOfString: [String] {
text.components(separatedBy: " ")
}
//If a user taps on a word it will be saved with its index
var userSelectedWords: [Int:String] = [2 : "a", 3 : "test", 4 : "for", 6 : "adjacent", 7 : "words", 9 : "the", 11 : "has"]
//Mapping all the keys into an array
var selectedKeys = userSelectedWords.map { $0.key }.sorted()
var indexToRemove = [Int]()
for i in 0..<selectedKeys - 1 {
//If the key has a value of one less that the succeding key, the words are adjacent
if selectedKeys[i] == selectedKeys[i + 1] - 1 {
indexToRemove.append(selectedKeys[i+1])
if let currentWord = userSelectedWords[selectedKeys[i]], let nextWord = userSelectedWords[selectedKeys[i + 1]] {
concatenatedString.append("(currentWord) (nextWord)")
}
}
}
print(indexToRemove)
//Prints: [3, 4, 7] which are the indexes that should be removed.
print(concatenatedString)
//Prints: ["a test", "test for", "adjacent words"]
/*
Here I'm stuck. If there are more than two words adjacent, the function will of
course continue the iteration and create a new item in the concatenatedString.
It feels like it starts to get way too complicated.
*/
我将非常感谢在这方面的任何输入或帮助。也许我只是看错了…
一种功能性的方法是基于连续排序的键创建Range
对象数组,然后过滤长度大于1的
let text = "This is a test for merging adjacent words that the user has selected."
let allWords = text.components(separatedBy: " ")
let userSelectedWords = [2 : "a", 3 : "test", 4 : "for", 6 : "adjacent", 7 : "words", 9 : "the", 11 : "has"]
let result = userSelectedWords.keys
.sorted()
.reduce(into: [Range]()) { ranges, index in
if let range = ranges.last, range.endIndex == index {
ranges[ranges.count - 1] = range.startIndex ..< index + 1
} else {
ranges.append(index ..< index + 1)
}
}
.filter { $0.count > 1 }
.map { allWords[$0].joined(separator: " ") }
print(result) // ["a test for", "adjacent words"]