lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Thu, Jul 16, 2009 at 8:03 PM, Petite Abeille<petite.abeille@gmail.com> wrote:
> Hello,
>
> Does anyone has a little function to compute the common prefix of a list of
> strings?
>
> E.g.:
>
> local aList = { 'foobarbaz', 'foobar', 'foo' }
>
> print( CommonPrefix( aList ) )
>
>> foo
>
> TIA.
>
> Cheers,
>
> PA.

Hi PA,

This is how I would do it:

--
local function commonprefix_aux(a,b,max)
  local count = 0
  for i = 1,max do
    if (string.sub(a,i,i) ~= string.sub(b,i,i)) then
      return count
    end
    count = count + 1
  end
  return count
end

function commonprefix(list)
  local first
  local prefixsize
  for i,v in ipairs(list) do
    if (i == 1) then
      first = v
      prefixsize = #first
    else
      prefixsize = math.min(prefixsize, commonprefix_aux(first,v,prefixsize))
      if (prefixsize == 0) then
        break
      end
    end
  end
  return string.sub(first or '',1,prefixsize or 0)
end
--

-Duncan