lua - Lua 打印在同一行
问题描述
这是我的代码。我想输出类似 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
推荐阅读
- c# - 使用 Visual Studio 和 Windows 窗体 (C#) 将文件上传和重命名到网络驱动器
- java - MenuItem 和图标图形 JavaFX 的大小和对齐方式
- javafx - 如何更改 TableView 行中的文本颜色?
- amazon-web-services - AWS DynamoDB filterexpression 具有多个带有 QueryRequest 的 IN 条件子句
- matlab - 如何在 Matlab 中显示所有自定义轴?
- firebase - Firebase - 数据库:如何根据用户限制对其他树的子级别的访问
- python - 使用 Python 获取流式视频 url 的图像
- javascript - 如何在 Blogger 上制作可排序的表格?
- python - 没有带有 waitress-serve 和 virtualenv 的名为 flask 的模块(App engine flex)
- c - 缓冲区溢出 shellcode 覆盖错误地址