close

Lua 的 split

Lua 的字串 split 整理 (split string in Lua)


function PrintLines(lines)
	for k,v in pairs(lines) do
		print('line['..k..'] = '..v)
	end
end

function split1(str, delimiter)
   local result = {}
   local fpat = "(.-)" .. delimiter
   local last_end = 1
   local s, e, cap = str:find(fpat, 1)
   while s do
      if s ~= 1 or cap ~= "" then
     table.insert(result,cap)
      end
      last_end = e+1
      s, e, cap = str:find(fpat, last_end)
   end
   if last_end <= #str then
      cap = str:sub(last_end)
      table.insert(result, cap)
   end
   return result
end

function split2(str, delimiter)
	result = {}
	for match in (str..delimiter):gmatch("(.-)"..delimiter) do 
		table.insert(result, match)
	end
	return result
end

function split3(str, delimiter)
	local result = {}
	string.gsub(str, '[^'..delimiter..']+', function(token) table.insert(result, token) end )
	return result
end

print("--test1")
lines1 = split1("1:2:3:4", ":")
PrintLines(lines1)
print("--test2")
lines2 = split2("str11:abc:3:5", ":")
PrintLines(lines2)
print("--test3")
lines3 = split3("331 asd 3 6", " ")
PrintLines(lines3)

20210814_lua_split_100.jpg

arrow
arrow
    文章標籤
    Lua split string
    全站熱搜

    kamory 發表在 痞客邦 留言(1) 人氣()