lua中string split函数
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 str = "1234,389,abc";
local list = Split(str, ",");
for i = 1, #list
do
str = string.format("index %d: value = %s", i, list[i]);
print(str);
end
方法二 可以改为string.split:
function split(str, delimiter) local result = {} local start = 1 local found = string.find(str, delimiter) while found ~= nil do table.insert(result, string.sub(str, start, found - 1)) start = found + #delimiter found = string.find(str, delimiter, start) end table.insert(result, string.sub(str, start)) return result end -- 使用示例: str = "Hello,World" delimiter = "," parts = split(str, delimiter) for i, part in ipairs(parts) do print(part) end
方法三:
使用正则表达式gmatch
function split(str, delimiter) local result = {} local start = 1 local found while true do found = str:gmatch("(" .. delimiter .. ")") if not found then break end local part = str:sub(start, found:len() - 1) table.insert(result, part) start = found:len() + 1 end table.insert(result, str:sub(start)) return result end -- 使用示例: str = "Hello,World" delimiter = "," parts = split(str, delimiter) for i, part in ipairs(parts) do print(part) end
实际上,使用正则表达式(在Lua中通常使用gmatch函数)来分割字符串并不会比使用string.split更快。string.split函数已经针对Lua的字符串处理进行了优化,并且在大多数情况下,它的执行速度已经足够快。
然而,如果你需要对一个非常大的字符串进行复杂的分割操作,或者需要使用正则表达式来匹配模式,那么使用gmatch可能会更合适。gmatch函数返回一个迭代器,可以用于在字符串中查找和匹配模式。