0

当主字符串超过 30 个字符并且我想使用的分隔符是字符之间的简单空格(主字符串中单词之间的最后一个空格)时,我试图将一个字符串拆分为 2 个字符串,因此它不会剪切单词。我正在向你们寻求帮助,因为我对 Lua 中的模式不是很好。

4

2 回答 2

5
local function split(str, max_line_length)
   local lines = {}
   local line
   str:gsub('(%s*)(%S+)', 
      function(spc, word) 
         if not line or #line + #spc + #word > max_line_length then
            table.insert(lines, line)
            line = word
         else
            line = line..spc..word
         end
      end
   )
   table.insert(lines, line)
   return lines
end

local main_string = 'This is very very very very very very long string'
for _, line in ipairs(split(main_string, 20)) do
   print(line)
end


-- Output
This is very very
very very very very
long string
于 2013-04-04T11:00:01.423 回答
0

如果您只想在单词之间的最后一个空格处拆分字符串,试试这个

s="How to split string by string length and a separator"
a,b=s:match("(.+) (.+)")
print(s)
print(a)
print(b)
于 2013-04-04T11:51:10.513 回答