Jump to content




Find all letters in a word?


  • You cannot reply to this topic
4 replies to this topic

#1 ChiknNuggets

  • Members
  • 130 posts

Posted 21 September 2012 - 01:46 PM

so what im trying to do is find the position of each of a certain letter in a word and then return it in a number, ive tryed so many different methods but it always seems to throw me an error or go into a infinite loop which is obviously not wanted, if anyone could help would be much appreciated

#2 MysticT

    Lua Wizard

  • Members
  • 1,597 posts

Posted 21 September 2012 - 02:02 PM

I'm not sure of what you're trying to do, but I'm sure that you'll need the string library (take a look at the find and match methods).

#3 ChiknNuggets

  • Members
  • 130 posts

Posted 21 September 2012 - 02:11 PM

Ive allready looked through all that before i posted, for example ive got the word elephant and i want to find all of the letter 'e' through out the word so in this case its letter 1 and 3, so i want a function that returns the number of each of the 'e' in the word. i tryed string.find but it seems to only give me one of them so...

#4 MysticT

    Lua Wizard

  • Members
  • 1,597 posts

Posted 21 September 2012 - 02:24 PM

Well, there might be some easier/better way, but this is what I came out with:
local function findAll(s, pattern, plain)
  local i = 1
  local result = {}
  while i < #s do
    local pos = string.find(s, pattern, i, plain)
    if not pos then
	  break
    end
    table.insert(result, pos)
    i = pos + 1
  end
  return result
end
It works like string.find but it returns a table with the starting positions of every match of the pattern.

So, you can use it like:
for _,i in ipairs(findAll("elephant", "e")) do
  print(i)
end
It will print 1 and 3.

#5 ChiknNuggets

  • Members
  • 130 posts

Posted 21 September 2012 - 02:39 PM

Ahh thank you, worked amazingly!





2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users