在Lua中分割字符串

机械摩根

我是Lua的新手,如果我听起来真的很愚蠢,对不起。我正在尝试制作一个执行以下操作的程序:

用户输入:“ Hello world” Var1:Hello Var2:world

因为我不知道我在做什么,所以我只剩下test = io.read(),而且我也不知道下一步该怎么做。

感谢您的帮助!

谢谢,摩根。

用户名

如果要分割单词,可以这样做:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章