我试图找到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"))
在这个例子中,我想打印"("因为此时新字符串不再与旧字符串一致。
如果有人对此有任何见解,我真的很感激。抱歉,我无法在代码方面提供更多工作,我不知道从哪里开始。
答案 0 :(得分:2)
只需遍历字符串,找到它们不匹配的时间。
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"))
答案 1 :(得分:0)
local function get_inserted_text(old, new)
local prv = {}
for o = 0, #old do
prv[o] = ""
end
for n = 1, #new do
local nxt = {[0] = new:sub(1, n)}
local nn = new:sub(n, n)
for o = 1, #old do
local result
if nn == old:sub(o, o) then
result = prv[o-1]
else
result = prv[o]..nn
if #nxt[o-1] <= #result then
result = nxt[o-1]
end
end
nxt[o] = result
end
prv = nxt
end
return prv[#old]
end
用法:
print(get_inserted_text("hello there", "hello.there")) --> .
print(get_inserted_text("hello there", "hello()there")) --> ()
print(get_inserted_text("hello there", "hello htere")) --> h
print(get_inserted_text("hello there", "heLlloU theAre")) --> LUA