Reputation: 85
I have a string "A001BBD0" and i want to know this info:
and that's it.
I found this pattern on web: "([a-zA-Z]).*(\1)" but it always returns nil for some reason
I guess i should split this string and check each symbol in several loops. I don't think this is a good idea (low performance)
i also found this topic but it doesn't give me any information
Upvotes: 4
Views: 4875
Reputation: 11
Here's an even shorter answer than the previous ones that I just came up with.
This is the simplest, and most efficient way to count repeating characters in a string on 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)
Upvotes: 1
Reputation: 194
Shorter version of the previous answer about use of the ternary operator
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
Upvotes: 1
Reputation: 964
Creating a record for each alphanumeric char will give a more generic solution
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
Upvotes: 2
Reputation: 72312
gsub
returns the number of substitutions. So, try this code:
function repeats(s,c)
local _,n = s:gsub(c,"")
return n
end
print(repeats("A001BBD0","0"))
print(repeats("A001BBD0","B"))
Upvotes: 9