Lua string.split

Lua自己实现string.split功能

---@field TableAux  table转字符串的辅助类
local TableAux = require("TableAux")

---拆分字符串
---@param str string 被拆分的源字符串
---@param sep string 拆分的
function string.split(str, sep)
    local result = {}
    if str == nil or sep == nil or type(str) ~= "string" or type(sep) ~= "string" then
        return result
    end

    if string.len(sep) == 0 then
        return result
    end
    local pattern = string.format("([^%s]+)", sep)
    --print(pattern)

    string.gsub(
        str,
        pattern,
        function(c)
            result[#result + 1] = c
        end
    )

    return result
end

local strres = "112||s|22s2"
local arr = string.split(strres, "|")
print(TableAux.TableToString(arr))

输出结果:

{
[1] = "112", 
[2] = "s",   
[3] = "22s2",
}

TableAuxhttps://blog.csdn.net/ZFSR05255134/article/details/123848580

猜你喜欢

转载自blog.csdn.net/ZFSR05255134/article/details/124015440