2016-09-26 126 views
2

我有由數字組成的字符串:在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 

但是,我想,這不是最有效的決定。我也可以將字符串轉換爲表和迭代表,但它似乎更加低效。那麼解決這個任務的最好方法是什麼?

+5

'str:gmatch「()2」' –

回答

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

要查找所有指數,也不要使用正則表達式,但僅僅是純文本搜索

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 
相關問題