gpt4 book ai didi

string - 在Lua中分割字符串并打印选定的键

转载 作者:行者123 更新时间:2023-12-02 09:54:49 26 4
gpt4 key购买 nike

我正在寻找使用 Lua 分割字符串并打印其中选定部分的一些帮助。到目前为止我有这个代码:

b = "an example string"

for i in string.gmatch(b, "%w+") do
print(i)
end

输出是...

  an
example
string

如何只打印结果的一部分?

我尝试了以下方法,但只返回了“nils”列表:

b = "an example string"

for i in string.gmatch(b, "%w+") do
print(i[1])
end

所以如果我想打印:

string
example

这将如何运作?我很确定我只是添加了分配给内存中键的值,例如 [0] 或 [1]。但我一定是错的..

在此用例中,示例文本将保持不变,只有字符串中的时间戳会发生变化。我只需要重新排序单词即可。

非常感谢任何帮助:)

最佳答案

我能找到的最好方法是使用循环将匹配项存储在数组中。然后您可以使用文字索引访问它们:

b = "an example string"

local words = {}
for i in string.gmatch(b, "%w+") do
table.insert(words, i)
end

print(words[3])
print(words[2])

关于string - 在Lua中分割字符串并打印选定的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57417080/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com