【问题标题】:What is the most efficient way to iterate numeric string in Lua?在 Lua 中迭代数字字符串的最有效方法是什么?
【发布时间】:2016-09-26 23:30:32
【问题描述】:

我有一个由数字组成的字符串:

str = "1234567892"

我想迭代其中的单个字符并获取特定数字的索引(例如,“2”)。据我所知,我可以使用gmatch 并创建一个特殊的迭代器来存储索引(因为据我所知,我无法使用gmatch 获取索引):

local indices = {}
local counter = 0
for c in str:gmatch"." do
    counter = counter + 1
    if c == "2" then
       table.insert(indices, counter)
    end
end

但是,我想,这不是最有效的决定。我也可以将字符串转换为表格并迭代表格,但它似乎效率更低。那么解决任务的最佳方法是什么?

【问题讨论】:

  • str:gmatch"()2"

标签: lua string-matching


【解决方案1】:

简单地循环字符串!你太复杂了:)

local indices = {[0]={},{},{},{},{},{},{},{},{},{}} --Remove [0] = {}, if there's no chance of a 0 appearing in your string :)
local str = "26842170434179427"

local container
for i = 1,#str do
    container = indices[str:sub(i, i)]
    container[#container+1] = i
end
container = nil

【讨论】:

    【解决方案2】:

    查找所有索引,也不使用正则表达式,而只是纯文本搜索

    local i = 0
    while true do
      i = string.find(str, '2', i+1, true)
      if not i then break end
      indices[#indices + 1] = i
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-28
      • 1970-01-01
      • 2020-10-24
      • 2012-02-12
      • 2015-07-14
      • 2013-05-17
      相关资源
      最近更新 更多