U
U
ufdhbi2020-10-31 13:17:22
Lua
ufdhbi, 2020-10-31 13:17:22

How to split a text string?

How to divide large text into lines of a certain length N in lua so that words are not cut off?
There is a sketch, but does not want to work

The code
function split(str, delim, plain)
    local tokens, pos, plain = {}, 1, not (plain == false)
    repeat
        local npos, epos = string.find(str, delim, pos, plain)
        table.insert(tokens, string.sub(str, pos, npos and npos - 1))
        pos = epos and epos + 1
    until not pos
    return tokens
end

function buildMessage(str, len)
    local words, temp, result = split(str, " "), "", {}
    for i, word in ipairs(words) do
        if temp:len() < len then
            if word:len() < (len - temp:len()) then
                if temp:sub(#temp, #temp):find("%s") or temp:len() == 0 then
                    temp = temp .. word
                else
                    temp = temp .. " " .. word
                end
            else
                table.insert(result, temp)
                temp = ""
            end
        end
    end
    return result
end

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Tomatov, 2020-12-14
@16tomatotonns

Well, for example like this:

local function split_by_lines(str, limit)
  local lines = {} -- результат
  local line = ""  -- текущая временная строка

  -- проходим по словам
  for word in (str .. " "):gmatch("(.-) ") do

    if #line + #word < limit then
      line = line .. " " .. word
    else
      table.insert(lines, line)
      line = word
    end
    
    -- чистим начальные и замыкающие пробелы, 
    -- чтобы не было мусора
    line = line:match("^%s*(.-)%s*$")
  end
  
  -- догоняем хвост
  table.insert(lines, line:match("^%s*(.-)%s*$"))
  return lines
end


local text = "This is the long long text that should be splitted by lines"
local result = split_by_lines(text, 15)
print( table.concat(result, "\n") )

> This is the
> long long text
> that should be
> splitted by
> lines

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question