如何按字符串长度和分隔符拆分字符串?

时间:2013-04-04 10:02:39

标签: lua split

当主字符串超过30个字符时,我正在尝试将字符串拆分为2个字符串,而我想要使用的分隔符是字符之间的简单空格(主字符串中单词之间的最后一个空格),因此它不会切换单词。我要求你们帮忙,因为我对Lua的模式不是很了解。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

如果您只想将字符串拆分为单词之间的最后一个空格,请尝试使用

s="How to split string by string length and a separator"
a,b=s:match("(.+) (.+)")
print(s)
print(a)
print(b)