1

我试图找出一种方法,到目前为止没有成功,将一个新行(“\n”)添加到一个非常长的字符串中。

是否有一个函数可以每 x 个字符插入一个新行?基本上,我需要每 95 个字符添加一个换行符。这是我正在使用的文本:

记录备忘录

主题:主题

1) Nam fabulas mnesarchum comprehensam ne, cu ullum euismod consulatu usu。Eam alii lobortis voluptatum id, denique eligendi pertinax quo ne。Vis congue eirmod ut。Duo probo 独家前。Elit pertinax abhorreant eu his, ipsum dicam dissentiunt pri id。Kasd erant dolorum id sed, ei vim partem deseruisse, ne mea dico tantas alienum。

2) 有 cu facilisis mediocritatem。Fabellas lucilius vim ex. Mei simul omnium et, wisi vidit ut ius。广告已诚实。Malis 动物无液体 id usu。

3) Nulla utinam appellantur cu qui, scripta sententiae disputando eu nam, ut pri unum labore。Odio wisi torquatos 海铜。Ut detracto torquatos repudiandae pri。Vim puto solum epicurei 在。Per nonummy perpetua similique te, odio platonem ut pri。Mei indoctum prodesset in, eam nisl quaerendum at。

4) 在 vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium v​​oluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga。Et harum quidem rerum facilis est et expedita distinctio。Nam libero tempore,cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus,omnis voluptas assumenda est,omnis dolor repellendus。

4

4 回答 4

2

我将这个问题解释为:我想将文本分成最多几行,但尽可能接近 95 个字符,以空格分隔。

我在其他答案中忽略了文件 IO。开始:

-- Second parameter governs where to break; defaults to 80.
-- Call me like: breakAt(longstring, 95)
local function breakAt(str, lineLength)
    local lineLength = lineLength or 80
    -- Arrays are more efficient for large text operations.
    local out = {}
    -- Match line without newlines; save original newlines.
    for line, breaks in str:gmatch('([^\n]+)(\n+)') do
        local count = 0
        -- Match whitespace with '*' to allow for the last word on the line having no adjacent whitespace.
        for word, whitespace in line:gmatch('(%S+)(%s*)') do
            count = count + #word
            if count > lineLength then
                -- If this word crosses the lineLength boundary, replace the last words' whitespace with a newline.
                out[#out] = '\n'
                -- The current word is the first on the new line.
                count = #word
            end
            count = count + #whitespace
            table.insert(out, word)
            table.insert(out, whitespace)
        end
        table.insert(out, breaks)
    end
    return table.concat(out)
end

这将打破空白处的字符串,最大化一行中的单词数。

于 2013-06-21T20:39:41.670 回答
1

这很简单!

local text = io.open'memorandum.txt':read'*a'  -- Load text from file
local n0, width = 0, 80
text = text:gsub('()(%s)',
    function(n, c)
        c = (n-n0 > width) and '\n' or c
        n0 = (c == '\n') and n or n0
        return c
    end)
io.open('memorandum2.txt','w'):write(text)  -- Save corrected text to file
于 2013-06-21T18:14:07.880 回答
0

这将直接输出任何短于 95 个字符的行,并将 95+ 个字符的行拆分为 94 个字符块,并附加换行符。它不会在空白处拆分,留给您作为练习。

local fout = io.output(os.getenv('userprofile').. '\\desktop\\temp.txt', 'w+');
for str in string.gmatch(text, '(.-\n)') do
    if str:len() > 95 then
        while str:len() > 95 do
            local s = str:sub(1, 94)
            fout:write(s.. '\n')
            str = str:sub(94)
        end
    else
        fout:write(str)
    end
end
fout:flush(); fout:close();
于 2013-06-21T17:50:15.137 回答
0

试试print(s:gsub("("..string.rep(".",95)..")","%1\n"))

但我怀疑你想对每一行都这样做,而不是对整个文本。

于 2013-06-21T17:36:30.873 回答