LUA:如何计算字符串中特定字符的出现次数?

我应该如何使用LUA计算字符串中特定字符的出现次数?

这里提供一个示例

让我们有一个字符串:“my|first|string|hello”

我想知道这个字符串中字符“|”出现的次数。 在这种情况下,它应该返回3。

请问我该如何处理?

点赞
用户14274597
用户14274597

最简单的解决方案就是逐个字符进行计数:

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
2021-07-21 16:16:21
用户7504558
用户7504558
`gsub` 返回第二个值中操作的数量。

local s = "my|fisrt|string|hello"

local _, c = s:gsub("|","") print(c) -- 3

```

2021-07-21 16:42:21