String "letter" position

Asked

Viewed 148 times

1

How can I get the position of a letter in a string. EX:

 a = "x  x  x"

I’d like to take the position of each x. I tried using the string.find, but he just took the one from the first one.

  • What real problem are you trying to solve?

2 answers

5


a = "x  x  x"

pos = 0
while 1 do
    pos = a:find( "x", pos + 1 )
    if not pos then break end
    print( pos )  -- poderia armazenar numa tabela
end

Exit:

1
4
7

See working on IDEONE.

3

Also try to

a = "x  x  x"
for k in a:gmatch("()x") do
    print(k)
end

Note the empty capture (), capturing the position.

  • 1

    I was hoping to see your solution, to see if you had more elegant ways to solve it. + 1 @Gabrielsales, consider considering this as accepted. Here is a test in IDEONE: http://ideone.com/S754jh

Browser other questions tagged

You are not signed in. Login or sign up in order to post.