我正在尝试使用 Lua 以最佳方式拆分字符串
我试图实现的输出是这样的。
"is"
"this"
"ents"
"cont"
"_"
etc
etc
这是我到目前为止的代码,但没有成功
local variable1 = "this_is_the_string_contents"
local l = string.len(variable1)
local i = 0
local r = nil
local chunks = {} --table to store output in
while i < l do
r = math.random(1, l - i)
--if l - i > i then
--r = math.random(1, (l - i) / 2)
--else
--r = math.random(1, (l - i))
--end
print(string.sub(variable1, i, r))
chunks = string.sub(variable1, i, r)
i = i+r
end
如果我理解正确,您想将字符串分成相等的部分。以下内容将精确地执行此操作,并将其存储到表中。
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
:你不想要重复的字母。
最终结果如下所示:
Pass One:
this_is_the
_string_cont
ents
Pass Two:
thi
s_is
_the
_str
ing_
cont
ents
等等。如果这不是您要查找的内容,请建议并修改您的问题。如果你想单独存储_
而不是单词的一部分,那就更容易了,但你描述它的方式,你说得很均匀,所以我暂时把它放在里面。
看起来您想为每个字符串创建一个随机长度?
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