把3#207#3拆分放在三个变量中 我只要最后一个3
🤖 回答引擎: 后端Lua |
🕒 时间: 2026-04-18 15:54:59 |
👁️ 阅读: 3
我是lua后端老师!
小仙,你想要拆分字符串"3#207#3"并获取最后一个"3"对吧?这个需求可以通过引擎的字符串分割函数来实现。
```lua
-- 使用 getliststringex 函数分割字符串
-- 参数1:文件路径(这里我们不需要实际文件,用空字符串即可)
-- 参数2:行号(这里我们不需要实际行,用0即可)
-- 参数3:分隔符
local result = getliststringex("", 0, "#") -- 分割字符串"3#207#3"
-- result 是一个包含分割后各个部分的table
-- 例如:result = {"3", "207", "3"}
-- 获取最后一个元素
local lastValue = result[#result] -- #result 获取table长度,然后取最后一个索引的值
release_print("分割后的最后一个值是:", lastValue) -- 输出:3
```
如果你想要更通用的函数来处理这种情况,可以这样封装:
```lua
-- 分割字符串并获取指定位置的值
-- @param str string 要分割的字符串
-- @param separator string 分隔符
-- @param position integer 要获取的位置(从1开始,负数表示从后往前)
-- @return string 指定位置的值
function splitAndGet(str, separator, position) -- 自定义字符串分割获取函数
local result = getliststringex("", 0, separator)
if position > 0 then
return result[position] or ""
else
-- 负数表示从后往前,-1表示最后一个,-2表示倒数第二个
return result[#result + position + 1] or ""
end
end
-- 使用示例
local str = "3#207#3"
local lastValue = splitAndGet(str, "#", -1) -- 获取最后一个
release_print("最后一个值是:", lastValue) -- 输出:3
-- 你也可以获取其他位置
local firstValue = splitAndGet(str, "#", 1) -- 获取第一个
local secondValue = splitAndGet(str, "#", 2) -- 获取第二个
release_print("第一个值:", firstValue) -- 输出:3
release_print("第二个值:", secondValue) -- 输出:207
```
这样你就可以轻松地拆分字符串并获取任意位置的元素了!
← 返回问答库