原创文章,欢迎转载,转载请注明:文章来自[寒江孤叶丶的CrossApp之旅系列]
博客地址:http://blog.youkuaiyun.com/qq446569365
工作需要自己封装了一个lua的字符串分割函数。为了方便自己以后使用。保存在这里。希望对其他开发者也有一些帮助吧……
---------------------------
-- @function StringSplit lua字符串分割函数
-- @param str 待分割的字符串
-- @param splitStr 用于分割字符串
-- @param addNemptyStr 是否将空字符串也放入返回字串表中(默认false,可空)
-- @param addSplitStrInTable 是否将分割用的字符串加入数组(默认false,可空)
-- @return 分割后字符串Table
-- Create by ArcherPeng
function StringSplit(str, splitStr,addNemptyStr,addSplitStrInTable)
if not addNemptyStr then addNemptyStr = false end
if not addSplitStrInTable then addSplitStrInTable = false end
local subStrTab = {};
while (true) do
local pos = string.find(str, splitStr);
if (not pos) then
if str ~="" or addNemptyStr then
subStrTab[#subStrTab + 1] = str;
end
break;
end
local subStr = string.sub(str, 1, pos - 1);
if subStr~="" or addNemptyStr then
subStrTab[#subStrTab + 1] = subStr;
end
if addSplitStrInTable then
subStrTab[#subStrTab + 1] = splitStr;
end
str = string.sub(str, pos +string.len(splitStr) , #str);
end
return subStrTab;
end
--test
print("---------")
local strTab=StringSplit("1233333456","33")
for index = 1,#strTab do
print(strTab[index])
end
print("---------")
strTab=StringSplit("1233333456","33",true)
for index = 1,#strTab do
print(strTab[index])
end
print("---------")
strTab=StringSplit("1233333456","33",true,true)
for index = 1,#strTab do
print(strTab[index])
end
print("---------")
strTab=StringSplit("1233333456","33",fasle,true)
for index = 1,#strTab do
print(strTab[index])
end
print("---------")
运行结果:
---------
12
3456
---------
12
3456
---------
12
33
33
3456
---------
12
33
33
3456
---------<span style="font-size:18px;">
</span>
另外推荐一个在线测试lua代码的网站:
http://www.lua.org/cgi-bin/demo
这样测试一些简单的函数时候就不用创建一个工程了………………(电脑上装了lua环境的请无视)