Lua 5.1 字符串分解函数 - 使用 string.gmatch 实现
在 Lua 5.1 中,你可以使用 string.gmatch 函数来分解字符串并传出字符串数组。string.gmatch 函数使用一个模式(正则表达式)来匹配字符串,并返回一个迭代器,该迭代器可以迭代所有匹配的字符串。\n\n以下是一个示例代码,展示如何使用 string.gmatch 函数来实现分解字符串并传出字符串数组:\n\nlua\nfunction splitString(str)\n local result = {}\n for match in string.gmatch(str, "[^%s]+") do\n table.insert(result, match)\n end\n return result\nend\n\n-- 示例用法\nlocal input = "Hello World Lua"\nlocal output = splitString(input)\nfor i, value in ipairs(output) do\n print(i, value)\nend\n\n\n输出:\n\n1 Hello\n2 World\n3 Lua\n\n\n在上面的示例中,splitString 函数接受一个字符串作为输入,并使用 string.gmatch 函数来循环匹配非空格的字符串。每次匹配到一个字符串时,将其插入到结果数组中。最后,返回结果数组。\n\n你可以根据自己的需求修改 splitString 函数中的模式,以适应不同的分解字符串要求。
原文地址: https://www.cveoy.top/t/topic/p2om 著作权归作者所有。请勿转载和采集!