将字符串按每个不超过26个字符的组分成表格,按最近的单词四舍五入

我正在尝试将一个字符串拆分成表格,每个索引包含最多26个字符,但单词不会在索引之间拆分。如果它在单词的中间超过了26个字符,那么该单词就在下一个索引中。

点赞
用户1442917
用户1442917

我曾经回答过一个类似的问题; 我确信你可以获取建议的实现并将其用于你的情况。你只需要返回表格而不是执行拼接操作:

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 00:14:42
用户6317920
用户6317920

将长度超过 wrap_length 的单词作为唯一可能溢出的单词,但是这种行为可以通过替换 or str:find'%s' 来自定义。

local function wrap_string(str, wrap_length)
  local lines = {}

  while #str > 0 do
    local last_space_index

    -- 仅检查比包装长度更长的子字符串
    if #str > wrap_length then
      -- 检查是否有第一个空格,以使长度大于 `wrap_length` 的单词不会被断开。
      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
2016-10-15 02:18:39