Search code examples
stringluacountsymbols

LUA count repeating characters in string


I have a string "A001BBD0" and i want to know this info:

  • 0 repeats 3 times
  • B repeats 2 times

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


Solution

  • 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