s = "this is a test string"
words = {}
for w in s:gmatch("%w+") do table.insert(words, w) end
使用此代碼我能夠分開每個單詞,但現在我需要能夠訪問只是第n個單詞。例如,我怎麼能打印第二個單詞?可能我把它轉換成數組莫名其妙然後使用類似的東西來如何在Lua中將字符串轉換爲數組?
print words[2]
s = "this is a test string"
words = {}
for w in s:gmatch("%w+") do table.insert(words, w) end
使用此代碼我能夠分開每個單詞,但現在我需要能夠訪問只是第n個單詞。例如,我怎麼能打印第二個單詞?可能我把它轉換成數組莫名其妙然後使用類似的東西來如何在Lua中將字符串轉換爲數組?
print words[2]
像這樣:
s = "this is a test string"
words = {}
for w in s:gmatch("%w+") do
table.insert(words, w)
end
print (words [2]) --> is
for k, v in ipairs (words) do
print (v)
end -- for
除了印刷 「是」 通過它遵循它:
is
a
test
string
print words[2]
只能省略括號的字符串文字和表格的構造函數,如:
print "hello, world"
print (table.getn { "the", "quick", "brown", "fox" }) --> 4
這不是真的,你只能省略字符串文字的parens,它也適用於表格構造函數。參見[BNF in the specs](http://www.lua.org/manual/5.3/manual.html#9):'args :: ='('[explist]')'| tableconstructor | LiteralString'。 – 2016-02-07 08:53:20
哦,是的,你是對的。 **和**表構造函數。我會修改我的帖子。 – 2016-02-07 08:59:26
你已經有答案了:'打印(字[2])'。 – 2014-10-08 17:11:54
它不起作用(「input:4:'='期望靠近'words'」) – 2014-10-08 17:12:40
編輯你用來完成的代碼。 – 2014-10-08 17:13:42