问题描述
这是我的代码。我想输出这样的东西 3,2,3,即在同一行中用逗号分隔的值,而不是在新行中获取值
我的输入是:@lua很有趣
谢谢!
function countChar(s)
words = {}
for word in s:gmatch("%w+")
do
table.insert(words,word)
print(#word)
end
end
n = tonumber(io.read())
for i=1,n
do
s=io.read();
countChar(s)
end
解决方法
您的代码存在问题:
-
words
表并未按原样使用。您只需要一个长度表,而不是单词表本身, - “解析”逻辑未与“用户界面”分开,
- 没有消息提示用户输入,
- 不需要的全局变量,
- 也可以保证
n
是带有io.read ('*number','*line')
的数字, - 可以使用
table.concat
将单词长打印在一行单词长表上。
这是我针对这些问题的建议:
local function countChar(s)
local lengths = {}
for word in s:gmatch '%w+' do
table.insert(lengths,word:len())
end
return lengths
end
io.write 'Number of sentences: '
local n = io.read('*number','*line')
for i = 1,n do
io.write ('Sentence no. ' .. tostring(i) .. ': ')
local s = io.read()
io.write ('Word lengths: ' .. table.concat(countChar(s),',') .. '\n')
end
此外,不需要提示用户输入句子的数量。在用户仅按Enter键(即插入一个空字符串)之前,可以逐个读取句子。此解决方案使用一个简单的迭代器,该迭代器消耗用户输入并显示提示:
local function countChar(s)
local lengths = {}
for word in s:gmatch '%w+' do
table.insert(lengths,word:len())
end
return lengths
end
local function getSentences()
io.write ('Enter a sentence or just press Enter to finish: ')
local input = io.read()
if input == '' then
input = nil -- this nil will stop the generic for loop below.
end
return input
end
for s in getSentences do
io.write ('Word lengths: ' .. table.concat(countChar(s),') .. '\n')
end
,
#! /usr/bin/env lua
local function countChar( str )
local numbers = ''
for word in str :gmatch( '%w+' ) do
numbers = numbers ..#word ..',' -- concatenate
end
return numbers :sub( 1,-2 ) -- remove trailing comma
end
io.write( 'Phrase to count? ' ) -- @lua is fun
local phrase = io .read()
print( countChar( phrase ) )
要数数吗? @lua很有趣
3,2,3