【问题标题】:LUA count repeating characters in stringLUA 计数字符串中的重复字符
【发布时间】:2019-04-12 02:53:11
【问题描述】:

我有一个字符串“A001BBD0”,我想知道这个信息:

  • 0 次重复 3 次
  • B 重复 2 次​​li>

就是这样。

我在网上找到了这种模式:“([a-zA-Z]).*(\1)”,但由于某种原因它总是返回 nil

我想我应该拆分这个字符串并在几个循环中检查每个符号。我认为这不是一个好主意(性能低下)

我还找到了this 主题,但它没有给我任何信息

【问题讨论】:

  • 顺便说一句,这是 Lua,不是 LUA。
  • 对不起)我不知道这很重要

标签: string lua count symbols


【解决方案1】:

gsub 返回替换的数量。所以,试试这个代码:

function repeats(s,c)
    local _,n = s:gsub(c,"")
    return n
end

print(repeats("A001BBD0","0"))
print(repeats("A001BBD0","B"))

【讨论】:

    【解决方案2】:

    为每个字母数字字符创建记录将提供更通用的解决方案

    local records = {} -- {['char'] = #number of occurances}
    s = "A001BBD0"
    for c in string.gmatch(s, "%w") do
        if records[c] then
            records[c] = records[c] + 1
        else
            records[c] = 1
        end
    end
    
    for k,v in pairs(records) do
        if(v > 1) then -- print repeated chars
            print(k,v)
        end
    end
    -- Output:
    -- 0    3
    -- B    2
    

    【讨论】:

    • 谢谢你,它有效。但现在我有另一个问题。我也使用俄语字母作为模式 [АВЕКМНОРСТУХ] 但由于某种原因它计数了两次。我不明白为什么
    • 哪些俄语字母被计算了两次?
    • А (这封信看起来像英文 A 但不是)当我打印俄语单词(毕竟函数)时,我不断得到空字符串(idk 为什么)。我尝试使用 string.byte/string.char 来避免这个问题 - 结果相同。我猜 Lua 不支持其他语言
    • 如果你想计算俄语字母(而不是其他字符,比如空格),你可能需要安装一个库,比如 luautf8,它包含 Lua 字符串匹配函数的版本其中 Cyrillic 与字符类 "%w" 匹配。或者您可以通过在本文的循环中将"%w" 替换为utf8.charpattern 来计算所有UTF-8 字符(假设您使用的是Lua 版本5.3),然后您将获得有关西里尔字符的信息。
    • string.gmatch(s, "[^%s%c%p\128-\191][\128-\191]*")替换string.gmatch(s, "%w")来处理俄语字母。
    【解决方案3】:

    上一个关于使用三元运算符的答案的简短版本

    local records = {}
    s = "A001BBD0"
    for c in string.gmatch(s, "%w") do
        records[c] = records[c] and records[c] + 1 or 1
    end
    
    for k,v in pairs(records) do
        if(v > 1) then -- print repeated chars
            print(k,v)
        end
    end
    

    【讨论】:

    • records[c] = (records[c] or 0) + 1
    【解决方案4】:

    这是一个比我刚刚想出的更短的答案。

    这是在 Lua 上计算字符串中重复字符的最简单、最有效的方法。

    local str = "A001BBD0"
    
    local count_0 = #string.gsub(str, "[^0]", "") -- count the 0's only
    local count_B_and_0 = #string.gsub(str, "[^B0]", "") -- count the B's and 0's together
    
    print(count_0, count_B_and_0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-07
      • 2022-01-02
      • 2021-03-25
      • 2017-07-09
      • 2016-05-20
      • 1970-01-01
      • 2017-09-03
      相关资源
      最近更新 更多