Lua字符串操作

时间:2013-06-21 17:30:28

标签: string lua

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

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

  

纪录备忘录

     

主题:主题

     

1)Nam fabulas mnesarchum comprehensam ne,cu ullum euismod consulatu usu。 Eam alii lobortis   意大利国民议会议员Vis congue eirmod ut。 Duo probo soleat ex。 Elit pertinax   憎恶他,ipsum dicam dissentiunt pri id。 Kasd erant dolorum id sed,ei vim partem deseruisse,   ne mea dico tantas alienum。

     

2)具有促进药物的作用。 Fabellas lucilius vim ex。 Mei simul omnium et,wisi vidit ut ius。   广告有erat honestatis。马利斯动物的液体是usu。

     

3)Nulla utinam appellantur cu qui,scripta sententiae disputando eu nam,ut pri unum labore。   Odio wisi torquatos sea cu。 Ut detracto torquatos repudiandae pri。 Vim puto solum epicurei at。   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   voluptatum 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。南   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 个答案:

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

这将打破空格上的字符串,最大化一行上的字数。

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

答案 2 :(得分:0)

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

但我怀疑你想为每个执行此操作,而不是为整个文本执行此操作。

答案 3 :(得分: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();