【问题标题】:Splitting strings in Lua在 Lua 中拆分字符串
【发布时间】:2018-06-01 00:25:15
【问题描述】:

我对 Lua 很陌生,如果我听起来很愚蠢,很抱歉。 我正在尝试制作一个有点像这样的程序:

用户输入:“Hello world” Var1:你好 Var2:世界

因为我不知道自己在做什么,所以我只有 test = io.read(),而且我不知道接下来要做什么。

感谢您的帮助!

谢谢,摩根。

【问题讨论】:

标签: lua


【解决方案1】:

如果你想要拆分单词,你可以这样做:

input = "Hello world"

-- declare a table to store the results
-- use tables instead of single variables, if you don't know how many results you'll have
t_result = {}

-- scan the input
for k in input:gmatch('(%w+)') do table.insert(t_result, k) end
-- input:gmatch('(%w+)')
-- with generic match function will the input scanned for matches by the given pattern
-- it's the same like: string.gmatch(input, '(%w+)')
-- meaning of the search pattern:
---- "%w" = word character
---- "+"  = one or more times
---- "()" = capture the match and return it to the searching variable "k"

-- table.insert(t_result, k)
-- each captured occurence of search result will stored in the result table

-- output
for i=1, #t_result do print(t_result[i]) end
-- #t_result: with "#" you get the length of the table (it's not usable for each kind of tables)
-- other way:
-- for k in pairs(t_result) do print(t_result[k]) end

输出:

Hello
world

【讨论】:

  • 非常感谢您的回答!但我真的不明白这是什么意思。如果不是太麻烦,您是否介意分解代码的每个部分的作用,以及如何将输出转换为变量?非常感谢您的回复。
  • 我现在添加了 cmets。如果结果计数未知,将结果存储在单个变量中是没有意义的。而当用户进行输入时,你不知道它会有多少字。
猜你喜欢
  • 2010-11-28
  • 1970-01-01
  • 2016-08-25
  • 2015-01-16
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多