Finding Amount of Specific Characters in a String

Hello, I am currently creating a function to find the amount of specified characters in a string. This is the current solution that I have.

local str = "jKa1sd1aSDd111sd1"

local function FindCharacters(txt)
	local input = txt
	local finds = 0
	local place = 0
	
	while true do
		if finds == 0 then
			if input:find('1') then
				finds = 1
				place = input:find('1') + 1
			else
				return 0
			end
		else
			if input:find('1', place) then
				finds += 1
				place = input:find('1', place) + 1
			else
				return finds
			end
		end
	end
	
end

print('Found '.. FindCharacters(str) .. ' matches.')  -- Found 6 matches. --

This solution works properly as intended, but I’m asking if there is any other way to do this or a specific function to do this more efficiently. Thanks for your time!

1 Like
local input = "abc123def45611addo1"
local output, count = input:gsub("1", "HONK")

print(count)

this prints 4

2 Likes

This works but makes a new, modified string. It’s possible to count occurrences without doing so, but it takes a bit more code:

local input = "abc123def45611addo111"

function count(iterator)
    local c = 0
    for _ in iterator do c = c + 1 end
    return c
end

function countMatches(string, pattern)
    return count(string:gmatch(pattern))
end

print(countMatches(input, "1")) --6

--A bit more manual approach
local matchesIter = input:gmatch("1")
print(count(matchesIter)) --6
2 Likes

Wow, that was really simple. I’ll make sure to put that discovery to use. :skull: