在Lua中,如果字符串中最多一个字符错误,请比较字符串。

我有一个单词,我想检查它是否等于另一个单词。如果是这样,那么一切都对了,但如果有一个(只有一个)错误的字符,它也可以是正确的。

local word = "table"
local word2 = "toble"
if word == word2 then
  print("Ok")
end

我该如何拆分 word2

点赞
用户1009479
用户1009479

你可以先比较字符串的长度,如果它们相等,那么就从第一个字符开始比较,如果有一个字符不同,那么剩下的字符必须相同才能满足你的条件:

function my_compare(w1, w2)
    if w1:len() ~= w2:len() then
        return false
    end
    for i = 1, w1:len() do
        if w1:sub(i, i) ~= w2:sub(i, i) then
            return w1:sub(i + 1) == w2:sub(i + 1)
        end
    end
    return true
end
2014-01-12 14:37:45