我尝试将一个字符串拆分成一个表,每个索引最多包含26个字符,但是单词不能在索引之间拆分。如果它在单词中间超过26个字符,那么该单词就会出现在下一个索引中。
发布于 2016-10-15 08:14:42
我以前使用过answered a similar question;我相信您可以获得建议的实现,并将其用于您的情况。您只需要返回表,而不是进行连接:
local function formatUpToX(s)
local x = 26
local splitstr = "([ \t]*)(%S*)([ \t]*)(\n?)"
local t = {""}
for prefix, word, suffix, newline in s:gmatch(splitstr) do
if #(t[#t]) + #prefix + #word > x and #t > 0 then
table.insert(t, word..suffix)
else
t[#t] = t[#t]..prefix..word..suffix
end
if #newline > 0 then table.insert(t, "") end
end
return t
end发布于 2016-10-15 10:18:39
只有比wrap_length更长的单词会溢出,但是可以通过替换or str:find'%s'来自定义这种行为。
local function wrap_string(str, wrap_length)
local lines = {}
while #str > 0 do
local last_space_index
-- Only check substrings longer than the wrap length
if #str > wrap_length then
-- Check for first space so words longer than `wrap_length` don't break.
last_space_index = str:sub(1, wrap_length):find'%s%S*$' or str:find'%s'
end
table.insert(lines, str:sub(1, last_space_index))
if not last_space_index then break end
str = str:sub(last_space_index + 1)
end
return lines
endhttps://stackoverflow.com/questions/40053505
复制相似问题