Title. How do you go about achieving this?
I know :find achieves a similar result, but it does not tell me how many times the keyword repeats itself in the string.
Title. How do you go about achieving this?
I know :find achieves a similar result, but it does not tell me how many times the keyword repeats itself in the string.
repeat string.find or :find and instead change the init:
local text = "I love tacos, tacos are my favourite!"
local patern = "taco"
local init = 1
local result1, result2 = string.find(text, patern, init)
every time you get results you check for the next one (just do init += 1)
for :find() use:
local result1, result2 = text:find(patern, init)
Here are some ways I found:
local function countSubstring(text, keyword)
local count = 0
for _ in text:gmatch(keyword) do
count += 1
end
return count
end
local function countSubstring(text, keyword)
local count = 0
text:gsub(keyword, function()
count += 1
end)
return count
end
local function countSubstring(text, keyword)
return select(2, text:gsub(keyword, ""))
end
local function countSubstring(text, keyword)
local _, count = text:gsub(keyword, "")
return count
end
local function countSubstring(text, keyword)
local count = 0
local init
repeat
_, init = text:find(keyword, init)
if init then count += 1 end
until init == nil
return count
end
You can then use the function like so:
print(countSubstring("I love tacos, tacos are my favourite!", "taco"))
you can simply do this instead for gsub
local function countSubstring(text, keyword)
local _, count = text:gsub(keyword, "")
return count
end
print(countSubstring("I love tacos, tacos are my favourite!", "taco"))
How do I make it search for two or more keywords?
Thanks btw
local function countSubstring(text, keywords)
local count = {}
for _, keyword in ipairs(keywords) do
count[keyword] = select(2, text:gsub(keyword, ""))
end
return count
end
print(countSubstring("abc def def", {"abc", "def"}))
OUTPUT
{
abc = 1,
def = 2
}
not sure if this is exactly what you want, but I hope it helps