Lua 中迭代数字字符串最有效的方法是什么?

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

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

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

点赞
用户2328287
用户2328287

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

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
2016-09-26 07:47:43
用户3979429
用户3979429

只需要简单地循环字符串即可!你正在过度复杂化它 :)

local indices = {[0]={},{},{},{},{},{},{},{},{},{}} --如果你的字符串中没有 0 的出现,可以删除 [0] = {}
local str = "26842170434179427"

local container
for i = 1,#str do
    container = indices[str:sub(i, i)]
    container[#container+1] = i
end
container = nil
2016-09-26 15:30:32