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

时间:2016-09-26 03:44:11

标签: lua string-matching

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

str = "1234567892"

我想在其中迭代单个字符并获取特定数字的索引(例如," 2")。正如我已经了解到的那样,我可以使用gmatch并创建一个特殊的迭代器来存储索引(因为据我所知,我只能用gmatch得到索引): / p>

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

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

2 个答案:

答案 0 :(得分:2)

简单地循环遍历字符串!你过度复杂了:)

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

答案 1 :(得分:1)

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

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
相关问题