Amir
Amir

Reputation: 2466

What is the most efficient way to iterate numeric string in Lua?

I have a string which consists of numbers:

str = "1234567892"

And I want to iterate individual characters in it and get indices of specific numbers (for example, "2"). As I've learned, I can use gmatch and create a special iterator to store the indices (because, as I know, I just can't get indices with 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

But, I guess, this is not the most efficient decision. I also can convert string to table and iterate table, but it seems to be even more inefficient. So what is the best way to solve the task?

Upvotes: 2

Views: 766

Answers (2)

warspyking
warspyking

Reputation: 3113

Simply loop over the string! You're overcomplicating it :)

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

Upvotes: 2

moteus
moteus

Reputation: 2235

To find all indices and also do not use regexp but just plain text search

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

Upvotes: 1

Related Questions