Difference between revisions of "String exploding"

Line 30: Line 30:
 
</source>
 
</source>
  
The following function is an alternative which will omit empty strings from the returned table if a delimiter(s) is leading or trailing the string being explodedThis means it will return a more compact table in some cases where the input string has excessive delimiters.  Due to these omissions, you won't be able to use table.concat to reverse it back into the original string.
+
The above function will potentially return a list peppered with empty strings if the original input string has leading, trailing or repeated delimitersThe following function is an alternative which will return a more compact table with these omitted.  Due to these omissions, you won't be able to use table.concat to reverse it back into the original string.
  
 
<source lang="lua">
 
<source lang="lua">

Revision as of 01:00, 6 April 2015

This function adds the ability to explode strings in Lua.

function string.explode(str, div)
    assert(type(str) == "string" and type(div) == "string", "invalid arguments")
    local o = {}
    while true do
        local pos1,pos2 = str:find(div)
        if not pos1 then
            o[#o+1] = str
            break
        end
        o[#o+1],str = str:sub(1,pos1-1),str:sub(pos2+1)
    end
    return o
end

Have an example:

tbl = string.explode("foo bar", " ")
print(tbl[1]) --> foo
-- since we added explode to the string table, we can also do this:
str = "foo bar"
tbl2 = str:explode(" ")
print(tbl2[2]) --> bar
-- to restore the original string, we can use Lua's table.concat:
original = table.concat(tbl, " ")
print(original) --> foo bar

The above function will potentially return a list peppered with empty strings if the original input string has leading, trailing or repeated delimiters. The following function is an alternative which will return a more compact table with these omitted. Due to these omissions, you won't be able to use table.concat to reverse it back into the original string.

function string.explode2(s, d)
  local t = {}
    repeat 
      local pos1, pos2 = string.find(s, d)
      t[#t + 1] = string.sub(s, 1, pos1 - 1)
      s = string.sub(s, pos2 + 1)
    until pos1 == nil
    if #s ~= 0 then t[#t+1] = s end
  return t
end