string - Lua将字符串拆分为表的键和值

标签 string lua split lua-table

所以我想拆分两个字符串,并能够返回一个表,其中一个字符串等于键,另一个字符串等于值。

所以如果:

String1 = "Key1,Key2,Key3,Key4,Key Ect..."
String2 = "Value1,Value2,Value3,Value4,Value Ect..."

输出将是如下表格:

Key1 - Value1
Key2 - Value2
Key3 - Value3
Key4 - Value4
Key Ect... - Value Ect...

我一直在研究在 Lua wiki 上找到的这个 split 函数

split(String2, ",")

function split(String, pat)
   local t = {}  -- NOTE: use {n = 0} in Lua-5.0
   local fpat = "(.-)" .. pat
   local last_end = 1
   local s, e, cap = str:find(fpat, 1)
   while s do
      if s ~= 1 or cap ~= "" then
     table.insert(t,cap)
      end
      last_end = e+1
      s, e, cap = str:find(fpat, last_end)
   end
   if last_end <= #str then
      cap = str:sub(last_end)
      table.insert(t, cap)
   end
   return t
end

但是当然这只会返回:

1 - Value1
2 - Value2

等等...

我将开始尝试修改此代码,但我不知道能修改到什么程度。

最佳答案

你可以像这样直接使用它:

local t1 = split(String1, ",")
local t2 = split(String2, ",")

local result = {}

for k, v in ipairs(t1) do
    result[v] = t2[k]
end

或者,创建您自己的迭代器:

local function my_iter(t1, t2)
    local i = 0
    return function() i = i + 1; return t1[i], t2[i] end
end

local result = {}

for v1, v2 in my_iter(t1, t2) do
    result[v1] = v2
end

关于string - Lua将字符串拆分为表的键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25656268/

相关文章:

javascript - 使用嵌套引号构建字符串

c++ - std::length_error 尝试从类数组输出字符串时

c - Lua - 数字到字符串的行为

python - 在没有 split() 的情况下在 Python 中拆分字符串

r - 修改一行数据以获得漂亮的输出(摘要), reshape - 将行拆分为新的多列

c - 为什么在 C 中不能使用 [] 为字符串分配内存?

c# - 这两种方法有什么区别?是什么让第二个比第一个更好?

Lua:替换一个子串

c++ - 错误 LNK2019 : Unresolved External Symbol _HUGE referenced in _luaopen_math

java - 解析电子邮件