Split string into table in groups of 26 characters or less, rounded to the nearest word

I'm trying to take a string and split it into a table, with each index containing a maximum of 26 characters, but words are not split between indices. If it stretches over 26 characters mid-word, that word is in the next index.

Answer1:

I've answered a similar question some time ago; I'm sure you can get the suggested implementation and use it for your case. You just need to return the table instead of doing the concatenation:

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

Answer2:

Words longer than wrap_length are the only words that will overflow, but that behavior can be customized by replacing 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 end

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:Split string into table in groups of 26 characters or less, rounded to the nearest word