在 Lua 中迭代数字字符串的最有效方法是什么?
What is the most efficient way to iterate numeric string in 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
但是,我想这不是最有效的决定。我也可以将字符串转换为 table 并迭代 table,但它似乎更加低效。那么解决任务的最佳方法是什么?
查找所有索引并且不使用正则表达式而仅使用纯文本搜索
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
我有一个由数字组成的字符串:
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
但是,我想这不是最有效的决定。我也可以将字符串转换为 table 并迭代 table,但它似乎更加低效。那么解决任务的最佳方法是什么?
查找所有索引并且不使用正则表达式而仅使用纯文本搜索
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