LUA: 计算一个字符在字符串中出现的次数?
LUA: count occurrences of a character into a string?
请问如何用 LUA 计算字符串中特定字符的出现次数?
我举个例子
让字符串:“my|fisrt|string|hello”
我想统计字符“|”出现了多少次有字符串。
在这种情况下,它应该 return 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
gsub
returns第二个值的运算次数
local s = "my|fisrt|string|hello"
local _, c = s:gsub("|","")
print(c) -- 3
请问如何用 LUA 计算字符串中特定字符的出现次数?
我举个例子
让字符串:“my|fisrt|string|hello”
我想统计字符“|”出现了多少次有字符串。 在这种情况下,它应该 return 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
gsub
returns第二个值的运算次数
local s = "my|fisrt|string|hello"
local _, c = s:gsub("|","")
print(c) -- 3