例如,我有一个字符串:
val string1 = "My friend gave me a gift"
,现在这个字符串被修改或编辑
val string1 = "My father gave me two gifts"
我如何知道字符串或句子中哪些地方发生了变化?
我一直在尝试这样做:
val oldString = prevString.split(" ")
val newString = currentText.split(" ")
for(i in oldString.indices) {
if (oldString[i] != newString[i]) {
oldText = oldString[i]
newText = newString[i]
}
}
但是通过这种方法,我只能找到字符串中的单个更改,而不是多个更改。有谁能帮我找到字符串的多个变化吗?
如果没有更多的细节,就不可能提出一个每次都能产生正确输出的算法。即使有一个精确的定义,这也可能是不可能的,因为我们处理的是语言。
如果确定两个字符串被一个空格分隔时具有相同的字数,那么这将是一种可能性:
val previousString = "My friend gave me a gift"
val currentText = "My father gave me two gifts"
val previousWords = previousString.split(" ")
val currentWords = currentText.split(" ")
val result = previousWords
.minus(currentWords)
.zip(currentWords.minus(previousWords))
println(result)
// Output: [(friend, father), (a, two), (gift, gifts)]
但是你很快就会陷入麻烦。一个例子:
val previousString = "My friend gave me a fantastic gift"
val currentText = "My father gave me two gifts"
生产:
[(friend, father), (a, two), (fantastic, gifts)]
…这当然是错误的。那标点符号呢?撇号呢?等等。