string - 查找两个字符串文本之间的 "difference"(Lua 示例)

标签 string algorithm lua difference levenshtein-distance

我试图找出 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/

相关文章:

c++ - Ruby vs Lua 作为 C++ 的脚本语言

java - 如何将 char[] 转换为字符串?

java - 正则表达式 - Java - 匹配字符串 (012|123|234|345|456|567|678|789|890)

java - 无限 strip 上索引的伪随机

从 lua 调用 C 函数

regex - 如果某些东西前面没有其他东西,则匹配

c++ - 指针、字符串和溢出错误

Javascript字符串替换某些字符

performance - 重复 W(n)= 2W(floor(n/2)) + 3

c++ - std::partition 调用两次以进行快速排序