lundi 18 septembre 2017

For a string that is too long in Lua, how can I split it intelligently?

I am trying to write a function that will split a string that is over a given length at the space that is nearest the string's midpoint. I have a largely functional one, but it has 2 issues. One, it feels overly complicated for what I want. Two, it can only split a string in half, not into 3 or 4 lines. I feel strongly that I must be missing something.

The function is below. s_original is the string, maxLineLength is how long the string is allowed to be before it triggers the split.

I'm replacing the space with a "/n" line break so my final product is one string, but having the strings split into a table would obviously also work great. I apprecaite any help.

function formatLineLength(s_original, maxLineLength)
    local length = #s_original
    if length > maxLineLength then
        --Split string into 2
        local midpoint = math.floor(length/2)
        local s_first = string.sub(s_original, 1, midpoint-1)
        local s_second = string.sub(s_original, midpoint)
        --Find last space (%s) in s_first
        local s_first_space = string.find(string.reverse(s_first), "%s")
        --Find first space in s_second
        local s_second_space = string.find(s_second, "%s")

        if s_first_space == nil and s_second_space == nil then
            --If both lengths are nil (no spaces)
            return s_first .. "\n" .. s_second
        elseif s_first_space ~= nil and s_second_space ~= nil then
            if s_first_space <= s_second_space then
                --If the space is closer in the first section
                local rev = string.reverse(s_first)
                return string.reverse(string.gsub(rev, "%s", "\n", 1)) .. s_second
            else
                --If the space is closer i nthe second section
                return s_first .. string.gsub(s_second, "%s", "\n", 1)
            end
        else
            if s_first_space == nil then
                --If there was no space in s_first
                return string.gsub(s_original, "%s", "\n", 1)
            else
                --If there was no space in s_second
                local rev = string.reverse(s_original)
                return string.reverse(string.gsub(rev, "%s", "\n", 1))
            end
        end
    else
        return s_original
    end
end

Aucun commentaire:

Enregistrer un commentaire