将字符串分成26个字符或更少的字符分成表格,四舍五入到最接近的单词 [英] Split string into table in groups of 26 characters or less, rounded to the nearest word
本文介绍了将字符串分成26个字符或更少的字符分成表格,四舍五入到最接近的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将一个字符串分割成一个表,每个索引最多包含26个字符,但单词未在两个索引之间分割.如果它在单词中间延伸超过26个字符,则该单词在下一个索引中.
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.
推荐答案
长于wrap_length
的单词是唯一会溢出的单词,但是可以通过替换or str:find'%s'
来自定义该行为.
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
这篇关于将字符串分成26个字符或更少的字符分成表格,四舍五入到最接近的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文