How can I find the words consist of the letters inside the keyword in Lua?

后端 未结 3 473
北恋
北恋 2021-01-24 02:30

For example, I have a keyword \"abandoned\" and I want to find the words that contains letters of this keyword such as \"done\", \"abandon\", band\", from the arrays I stored t

相关标签:
3条回答
  • 2021-01-24 03:07

    Try this:

    W={"done", "abandon", "band"}
    for k,w in pairs(W) do
        W[w]=true
    end
    
    function findwords(s)
        for i=1,#s do
            for j=i+1,#s do
                local w=s:sub(i,j)
                if W[w] then print(w) end
            end
        end
    end
    
    findwords("abandoned")
    

    If you don't have an array of words, you can load a dictionary:

    for w in io.lines("/usr/share/dict/words") do
        W[w]=true
    end
    
    0 讨论(0)
  • 2021-01-24 03:17

    For example, I have a keyword "abandoned" and I want to find the words that contains letters of this keyword such as "done", "abandon", band", from the arrays I stored those words. How can I search it?

    You can simply use the keyword as a regular expression (aka "pattern" in Lua), using it's letters as a set, for instance ('^[%s]+$'):format('abandoned'):match('done').

    local words = {'done','abandon','band','bane','dane','danger','rand','bade','rand'}
    local keyword = 'abandoned'
    
    -- convert keyword to a pattern and match it against each word
    local pattern = string.format('^[%s]+$', keyword)
    for i,word in ipairs(words) do
        local matches = word:match(pattern)
        print(word, matches and 'matches' or 'does not match')
    end
    

    Output:

    done    matches
    abandon matches
    band    matches
    bane    matches
    dane    matches
    danger  does not match
    rand    does not match
    bade    matches
    rand    does not match
    
    0 讨论(0)
  • 2021-01-24 03:18

    Run the loop on your arrays and use string.find to check against this long word.

    for idx = 1, #stored_words do
       local word = stored_words[idx]
       if string.find(long_word, word, 1, true) then
          print(word .. " matches part of " .. long_word)
       end
    end
    
    0 讨论(0)
提交回复
热议问题