把lua分割成单词。

我有一串 Lua 字符串。

它由一系列的 [a-zA-Z0-9]+ 字符和数字(1 或更多)空格隔开。

我该如何将这个字符串分割并转成字符串表?

原文链接 https://stackoverflow.com/questions/2779700

点赞
stackoverflow用户107090
stackoverflow用户107090
s="如何将字符串拆分为字符串表?"
for w in s:gmatch("%S+") do print(w) end
2010-05-06 10:03:35
stackoverflow用户206020
stackoverflow用户206020
s = "foo bar 123"
words = {}
for word in s:gmatch("%w+") do table.insert(words, word) end
s = "foo bar 123"
words = {}
for word in s:gmatch("%w+") do table.insert(words, word) end

将给定字符串's'中的单词添加到'table'(一个空表)中。在这个循环中,使用'gmatch'函数匹配输入字符串中的单词并将其添加到表中。

2010-05-06 10:03:55
stackoverflow用户12968803
stackoverflow用户12968803

以下是如何分割单词并合并它们的示例:

function mergeStr (strA, strB)
  local tablA, tablB = {}, {}
  for word in strA:gmatch("%S+") do
    table.insert (tablA, word)
  end
  for word in strB:gmatch("%S+") do
    table.insert (tablB, word)
  end
  return tablA[1] .. ' ' .. tablB[3] .. ' ' .. tablA[5]
end

print (mergeStr ("Lua is a programming language", "I love coding"))
-- "Lua coding language"
2023-02-27 11:21:29