我试图找出 Lua 中两个字符串值之间的文本差异,但我不太确定如何有效地做到这一点。我在使用字符串模式方面并不是很有经验,我确信这是我在这方面的失败。这是一个例子:
-- Original text
local text1 = "hello there"
-- Changed text
local text2 = "hello.there"
-- Finding the alteration of original text with some "pattern"
print(text2:match("pattern"))
在上面的示例中,我想输出文本“.”,因为这是两个文本之间的区别。对于差异可能对字符串模式敏感的情况也是如此,如下所示:
local text1 = "hello there"
local text2 = "hello()there"
print(text2:match("pattern"))
在此示例中,我想打印“(”,因为此时新字符串不再与旧字符串一致。
如果有人对此有任何见解,我将非常感激。抱歉,我无法提供更多的代码方面的工作,我只是不知道从哪里开始。
最佳答案
只需迭代字符串并查找它们何时不匹配。
function StringDifference(str1,str2)
for i = 1,#str1 do --Loop over strings
if str1:sub(i,i) ~= str2:sub(i,i) then --If that character is not equal to it's counterpart
return i --Return that index
end
end
return #str1+1 --Return the index after where the shorter one ends as fallback.
end
print(StringDifference("hello there", "hello.there"))
关于string - 查找两个字符串文本之间的 "difference"(Lua 示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41513059/