我是lua的新手,我想弄清楚如何按字母顺序重新排列字符串。例如,如果字符串为“ APPLE”,则我的代码应返回“ AELPP”。我该如何实现?谢谢
答案 0 :(得分:2)
您应该:
例如:
local str = "APPLE"
local tab = {}
str:gsub(".",function(c) table.insert(tab,c) end)
table.sort(tab)
str = table.concat(tab)
print(str)
答案 1 :(得分:2)
local function sort(input)
local buffer = {}
for i=1,#subject do
buffer[i] = subject:sub(i,i)
end
table.sort(buffer)
return table.concat(buffer)
end
print(sort("Lorem ipsum dolor sit amet"))
这不是最“优雅”的解决方案,但是相对于与gmatch
和gsub
循环,它在Lua 5.3上进行基准测试无疑是最快的。
gsub took 0.278914 seconds
gmatch took 0.260757 seconds
numfor took 0.228867 seconds
对于LuaJIT 2.1,结果非常相似:
gsub took 0.167457 seconds
gmatch took 0.157505 seconds
numfor took 0.124351 seconds
基准详细信息:在长度为4300个字符的字符串上调用的全部功能重复100次。所有函数均承担排序和连接的共同开销,因此仅循环结构的性能差异就大于数字所示的结果。