LUA 统计字符串中重复的字符

我有一个字符串"A001BBD0",我想知道这些信息:

  • 0 重复出现了 3 次
  • B 重复出现了 2 次

就这些了。

我在网上找到了这个模式:"([a-zA-Z]).*(\1)",但它总是返回 nil

我想我应该分割这个字符串,并在几个循环中检查每个符号。我认为这不是一个好主意(效率低)

我还发现了这个主题,但它并没有给我任何信息

点赞
用户107090
用户107090

gsub 返回替换的次数。因此,试试这段代码:

function repeats(s,c)
    local _,n = s:gsub(c,"")
    return n
end

print(repeats("A001BBD0","0"))
print(repeats("A001BBD0","B"))
2018-11-08 15:11:48
用户5525442
用户5525442

使用每个字母数字字符创建一条记录将提供更通用的解决方案

local records = {} -- {['char'] = #number of occurances}
s = "A001BBD0"
for c in string.gmatch(s, "%w") do
    if records[c] then
        records[c] = records[c] + 1
    else
        records[c] = 1
    end
end

for k,v in pairs(records) do
    if(v > 1) then -- 打印重复的字符
        print(k,v)
    end
end
-- 输出:
-- 0    3
-- B    2
2018-11-08 15:29:40
用户9669614
用户9669614

使用三目运算符的先前答案的简短版本

local records = {}
s = "A001BBD0"
for c in string.gmatch(s, "%w") do
    records[c] = records[c] and records[c] + 1 or 1
end

-- 打印重复的字符
for k,v in pairs(records) do
    if(v > 1) then
        print(k,v)
    end
end
2018-11-09 06:19:47
用户17143286
用户17143286

以下是比之前更简短的答案。

这是在Lua中计算字符串中重复字符的最简单、最高效的方法。

local str = "A001BBD0"

local count_0 = #string.gsub(str, "[^0]", "") -- 只计算0的数量
local count_B_and_0 = #string.gsub(str, "[^B0]", "") -- 计算B和0的数量

print(count_0, count_B_and_0)
2021-10-13 14:00:29