Lua分割字符串并将输出放入表中

我正在尝试使用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
点赞
用户308010
用户308010

如果我理解你的问题正确,你想将一个字符串划分为相等的部分。下面的代码既可以实现这个功能,还可以将结果存储到表中。

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: 你不想重复字母。

最终结果如下:

第一部分:
this_is_the
_string_cont
ents

第二部分:
thi
s_is
_the
_str
ing_
cont
ents

如此类推。如果这不是你要的,那请说明并修改你的问题。如果你想把下划线_单独存储而不是作为单词的一部分,那更容易,但是根据你的描述,你说要平均分割,所以我暂时将其保留。

2020-02-08 03:35:09
用户2705567
用户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