Разделите строку на куски заданного размера без разрыва слов
Мне нужно разбить строку на куски в соответствии с определенным размером. Я не могу сломать слова между кусками, поэтому мне нужно поймать, когда добавление следующего слова переместит размер блока и запустит следующий (это нормально, если кусок меньше заданного размера).
Вот мой рабочий код, но я хотел бы найти более элегантный способ сделать это.
def split_into_chunks_by_size(chunk_size, string)
string_split_into_chunks = [""]
string.split(" ").each do |word|
if (string_split_into_chunks[-1].length + 1 + word.length > chunk_size)
string_split_into_chunks << word
else
string_split_into_chunks[-1] << " " + word
end
end
return string_split_into_chunks
end
Ответы
Ответ 1
Как насчет:
str = "split a string into chunks according to a specific size. Seems easy enough, but here is the catch: I cannot be breaking words between chunks, so I need to catch when adding the next word will go over chunk size and start the next one (its ok if a chunk is less than specified size)."
str.scan(/.{1,25}\W/)
=> ["split a string into ", "chunks according to a ", "specific size. Seems easy ", "enough, but here is the ", "catch: I cannot be ", "breaking words between ", "chunks, so I need to ", "catch when adding the ", "next word will go over ", "chunk size and start the ", "next one (its ok if a ", "chunk is less than ", "specified size)."]
Обновление после комментария @sawa:
str.scan(/.{1,25}\b|.{1,25}/).map(&:strip)
Это лучше, так как не требуется, чтобы строка заканчивалась символом \W
И он будет обрабатывать слова длиннее указанной длины. На самом деле это будет их разделение, но я предполагаю, что это желаемое поведение.
Ответ 2
@Yuriy, ваше чередование выглядит как проблема. Как насчет:
str.scan /\S.{1,24}(?!\S)/
#=> ["split a string into", "chunks according to a", "specific size. Seems easy", "enough, but here is the", "catch: I cannot be", "breaking words between", "chunks, so I need to", "catch when adding the", "next word will go over", "chunk size and Start the", "next one (its ok if a", "chunk is less than", "specified size)."]