Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Lua中迭代数字字符串最有效的方法是什么?_Lua_String Matching - Fatal编程技术网

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

在Lua中迭代数字字符串最有效的方法是什么?,lua,string-matching,Lua,String Matching,我有一个由数字组成的字符串: str = "1234567892" 我想迭代其中的单个字符,并获得特定数字的索引(例如,“2”)。据我所知,我可以使用gmatch并创建一个特殊的迭代器来存储索引(因为,正如我所知,我无法使用gmatch获取索引): 但是,我想,这不是最有效的决定。我还可以将字符串转换为表和迭代表,但效率似乎更低。那么,解决此任务的最佳方法是什么呢?查找所有索引,并且不使用regexp,只使用纯文本搜索 local i = 0 while true do i = strin

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

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


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

查找所有索引,并且不使用regexp,只使用纯文本搜索

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

只需在字符串上循环!你把它复杂化了:)

str:gmatch“()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
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