如何使用LUA将特定字符的出现次数计数到字符串中?
我在这里举一个的例子
让字符串:"my|fist|string|hello">
我想数一下出现了多少个字符"|"具有字符串。在这种情况下,它应该返回3
我该怎么做?
gsub
返回第二个值中的操作数
local s = "my|fisrt|string|hello"
local _, c = s:gsub("|","")
print(c) -- 3
最简单的解决方案就是逐字符计数:
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
或者,计算你的角色的所有匹配:
local count = 0
local string = "my|fisrt|string|hello"
for i in string:gmatch("|") do
count = count + 1
end