最近在用lua語(yǔ)言寫一個(gè)工具,遇見了一個(gè)問(wèn)題,獲取到了str="1,2,3,4,5 " 這樣的 字符串 ,想要將str轉(zhuǎn)換成table進(jìn)行處理,以下代碼就可以實(shí)現(xiàn),type(list) is table
function Split(szFullString, szSeparator)
local nFindStartIndex = 1
local nSplitIndex = 1
local nSplitArray = {}
while true do
local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex)
if not nFindLastIndex then
nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len(szFullString))
break
end
nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1)
nFindStartIndex = nFindLastIndex + string.len(szSeparator)
nSplitIndex = nSplitIndex + 1
end
return nSplitArray
end
用法:
local list = Split("abc,123,345", ",")
--然后list里面就是
abc
123
345
第二個(gè)參數(shù)可以是多個(gè)字符,但是不能是Lua正則表達(dá)式。例如. ,或者 %w 之類的。