lua-users home
lua-l archive

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


On Fri, Jul 17, 2009 at 2:56 PM, Andre<arpin@kingston.net> wrote:
> Petite Abeille <petite.abeille <at> gmail.com> writes:
>
>>
>> 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.
>>
>> P.S.
>>
>
> I think this is really a matching problem

I can't see any reason to use:

  string.match(v, '^'..prefix)

...instead of:

  (string.sub(v,1,#prefix)==prefix)

...and using match also has the disadvantage that your prefix cannot
include any of the "magic" matching characters like . [ ] % etc. Of
course you can use a gsub to prefix these with % beforehand.

Also I have a simpler suggested implementation to replace my earlier one:

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

-Duncan