2013-06-21 6 views
1

Я пытаюсь найти способ, пока безуспешно, добавить новую строку («\ n») к очень длинной строке.Операция строки Lua

Есть функция, которая будет вставлять новую строку каждые x количество символов? В принципе, мне нужно добавить новую строку каждые 95 символов. Вот текст, я работаю с:

МЕМОРАНДУМ ДЛЯ ЗАПИСИ

ПРЕДМЕТ: Тема

1) Нам fabulas mnesarchum comprehensam пе, у.е. ullum euismod consulatu усу. Eam alii lobortis voluptatum id, denique eligendi pertinax quo ne. Vis congue eirmod ut. Duo probo soleat ex. 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. Fabella lucilius vim ex. Mei simul omnium et, wisi vidit ut ius. Объявление имеет честность. Malis животное aliquid id usu.

3) Nulla utinam appellantur cu qui, scripta sententiae contestando eu nam, ut pri unum labore. Odio wisi torquatos море cu. Ut detracto torquatos repudiandae pri. Vim puto solum epicurei at. За безмятежность perpetua similique te, odio platonem ut pri. Mei indoctum prodesset in, eam nisl quaerendum at.

4) При Vero ЭОС и др accusamus ET iusto Одио dignissimos ducimus Qui blanditiis praesentium voluptatum deleniti atque corrupti quos ДОЛОРЕС и др Quas molestias excepturi SINT occaecati cupiditate не бережливый, similique Sunt в Culpa Qui officia deserunt mollitia Animi, ID Текущая labum et dolorum fuga. Et harum quidem rerum facilis est et rapidita distinctio. Nam libero tempore, сперма soluta nobis est eligendi optio cumque nihil препятствует quo минус id quod maxime placeat facere possimus, omnis voluptas precenda est, omnis dolor repellendus.

ответ

0

Пробег: print(s:gsub("("..string.rep(".",95)..")","%1\n")).

Но я подозреваю, что вы хотите сделать это для каждой линии линии, а не для всего текста.

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(); 
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 
+0

Вы можете добавить ': close()' в последнюю строку. – lhf

+0

@lhf - К сожалению, он работает только в Lua 5.2. В любом случае файл будет автоматически закрыт при выходе из программы. –

+0

Право, Lua 5.2. – lhf

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 

Это сломает строку в пробеле, максимизируя количество слов в строке.

+0

Ключевое слово 'break' не может использоваться как имя функции в Lua , –

+0

Действительно, он не может. Исправлена. – jpflorijn

Смежные вопросы