请问如何使用LUA计算字符串中特定字符的出现次数?
我在这里举一个例子
让字符串:“my|fisrt|string|hello”
我想统计字符“|”出现了多少次 有字符串。在这种情况下,它应该返回 3
请问我该怎么办?
gsub返回第二个值中的运算次数
local s = "my|fisrt|string|hello"
local _, c = s:gsub("|","")
print(c) -- 3
Run Code Online (Sandbox Code Playgroud)
最简单的解决方案就是逐个字符地计数:
local count = 0
local string = "my|fisrt|string|hello"
for i=1, #string do
if string:sub(i, i) == "|" then
count = count + 1
end
end
Run Code Online (Sandbox Code Playgroud)
或者,计算您的角色的所有匹配项:
local count = 0
local string = "my|fisrt|string|hello"
for i in string:gmatch("|") do
count = count + 1
end
Run Code Online (Sandbox Code Playgroud)