Lua分割字符串并将输出放入表中
2020-2-7 19:32:16
收藏:0
阅读:185
评论:2
我正在尝试使用Lua以最佳方式分割字符串
我想要实现的输出是这样的。
"is"
"this"
"ents"
"cont"
"_"
等等
等等
这是迄今为止没有成功的代码
local variable1 = "this_is_the_string_contents"
local l = string.len(variable1)
local i = 0
local r = nil
local chunks = {} --用于存储输出的表
while i < l do
r = math.random(1, l - i)
--如果l-i>i,则
--r = math.random(1, (l - i) / 2)
--否则
--r = math.random(1, (l - i))
--结束
print(string.sub(variable1, i, r))
chunks = string.sub(variable1, i, r)
i = i+r
end
点赞
用户2705567
看起来你想要为每个字符串创建一个随机长度?
function GetRandomStringList(str)
local str_table = {}
while string.len(str)>0 do
local str_chunk_size = math.random(1,string.len(str))
table.insert(str_table,string.sub(str,1,str_chunk_size))
str=string.sub(str,str_chunk_size+1)
end
return str_table
end
function DisplayStringList(name, str_table)
print(name..":")
for loop=1,#str_table do
print(str_table[loop])
end
print("")
end
do
local str = "this_is_the_string_contents"
DisplayStringList("first", GetRandomStringList(str))
DisplayStringList("second", GetRandomStringList(str))
DisplayStringList("third", GetRandomStringList(str))
end
我简单地循环,只要字符串中仍然存在字符,就随机选择一个块大小,将字符串的该部分插入表中,然后从字符串中删除该部分。重复。当字符串为空时,将表返回给调用者进行处理。
输出看起来像:
first:
t
his_is_the_stri
ng_
content
s
second:
this_is_the_s
tring
_contents
third:
this_is_the_string_cont
ent
s
2020-02-08 04:21:05
评论区的留言会收到邮件通知哦~
推荐文章
- Lua 虚拟机加密load(string.dump(function)) 后执行失败问题如何解决
- 我想创建一个 Nginx 规则,禁止访问
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?

如果我理解你的问题正确,你想将一个字符串划分为相等的部分。下面的代码既可以实现这个功能,还可以将结果存储到表中。
local variable2 = "this_is_the_string_contents" math.randomseed(os.time()) local l = #variable2 local i = 0 local r = math.random(1, l/2) local chunks = {} while i <= l+5 do print(variable2:sub(i, i+r)) table.insert(chunks, variable2:sub(i,i+r)) i = i+r+1 end每次运行脚本时更改
math.randomseed是一个好习惯,这样可以获得更多的随机数变化。下面是一些代码细节的说明:local r = math.random(1, l/2): 你可以将2改成任何你想要的数字,但这样做可以防止脚本将#variable2作为字符串长度,从而允许将变量作为单个块。while i <= l+5 do: 我添加了+5以处理某些超出范围的情况,只是作为一种预防措施。table.insert(chunks, variable2:sub(i, i+r)): 这是需要插入到表中的内容。由于我们需要等量的部分,所以您将使用i+r作为尾部。i = i+r+1: 你不想重复字母。最终结果如下:
如此类推。如果这不是你要的,那请说明并修改你的问题。如果你想把下划线
_单独存储而不是作为单词的一部分,那更容易,但是根据你的描述,你说要平均分割,所以我暂时将其保留。