首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将字符串拆分成不超过26个字符的组,四舍五入到最接近的单词

将字符串拆分成不超过26个字符的组,四舍五入到最接近的单词
EN

Stack Overflow用户
提问于 2016-10-15 07:46:19
回答 2查看 74关注 0票数 2

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

EN

Stack Overflow用户

发布于 2016-10-15 10:18:39

只有比wrap_length更长的单词会溢出,但是可以通过替换or str:find'%s'来自定义这种行为。

代码语言:javascript
运行
复制
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
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40053505

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档