LUA 计算字符串中的重复字符
LUA count repeating characters in string
我有一个字符串 "A001BBD0",我想知道这个信息:
- 0次重复3次
- B重复2次
就是这样。
我在网上找到了这个模式:“([a-zA-Z]).*(\1)”但由于某种原因它总是 returns nil
我想我应该拆分这个字符串并在多个循环中检查每个符号。我不认为这是个好主意(低性能)
我也找到了 this 主题,但它没有给我任何信息
gsub
returns 换人次数。所以,试试这个代码:
function repeats(s,c)
local _,n = s:gsub(c,"")
return n
end
print(repeats("A001BBD0","0"))
print(repeats("A001BBD0","B"))
为每个字母数字字符创建一条记录将提供更通用的解决方案
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 repeated chars
print(k,v)
end
end
-- Output:
-- 0 3
-- B 2
先前关于使用三元运算符的答案的简短版本
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 repeated chars
print(k,v)
end
end
这里的答案比我刚才想出的答案更短。
这是计算 Lua 上字符串中重复字符的最简单、最有效的方法。
local str = "A001BBD0"
local count_0 = #string.gsub(str, "[^0]", "") -- count the 0's only
local count_B_and_0 = #string.gsub(str, "[^B0]", "") -- count the B's and 0's together
print(count_0, count_B_and_0)
我有一个字符串 "A001BBD0",我想知道这个信息:
- 0次重复3次
- B重复2次
就是这样。
我在网上找到了这个模式:“([a-zA-Z]).*(\1)”但由于某种原因它总是 returns nil
我想我应该拆分这个字符串并在多个循环中检查每个符号。我不认为这是个好主意(低性能)
我也找到了 this 主题,但它没有给我任何信息
gsub
returns 换人次数。所以,试试这个代码:
function repeats(s,c)
local _,n = s:gsub(c,"")
return n
end
print(repeats("A001BBD0","0"))
print(repeats("A001BBD0","B"))
为每个字母数字字符创建一条记录将提供更通用的解决方案
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 repeated chars
print(k,v)
end
end
-- Output:
-- 0 3
-- B 2
先前关于使用三元运算符的答案的简短版本
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 repeated chars
print(k,v)
end
end
这里的答案比我刚才想出的答案更短。
这是计算 Lua 上字符串中重复字符的最简单、最有效的方法。
local str = "A001BBD0"
local count_0 = #string.gsub(str, "[^0]", "") -- count the 0's only
local count_B_and_0 = #string.gsub(str, "[^B0]", "") -- count the B's and 0's together
print(count_0, count_B_and_0)