Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert line breaks in long string -- word wrap

Tags:

string

r

Here is a function I wrote to break a long string into lines not longer than a given length

strBreakInLines <- function(s, breakAt=90, prepend="") {   words <- unlist(strsplit(s, " "))   if (length(words)<2) return(s)   wordLen <- unlist(Map(nchar, words))   lineLen <- wordLen[1]   res <- words[1]   lineBreak <- paste("\n", prepend, sep="")   for (i in 2:length(words)) {     lineLen <- lineLen+wordLen[i]     if (lineLen < breakAt)        res <- paste(res, words[i], sep=" ")     else {       res <- paste(res, words[i], sep=lineBreak)       lineLen <- 0     }   }   return(res) } 

It works for the problem I had; but I wonder if I can learn something here. Is there a shorter or more efficient solution, especially can I get rid of the for loop?

like image 964
Karsten W. Avatar asked Feb 28 '10 16:02

Karsten W.


People also ask

How do you insert a line break in text?

To add spacing between lines or paragraphs of text in a cell, use a keyboard shortcut to add a new line. Click the location where you want to break the line. Press ALT+ENTER to insert the line break.

How do I force a line break in a text box?

Of course, there are situations in which there is need to add line breaks. You can do so by simply hitting Shift + Return or Shift + Enter , respectively.

How do you insert a hard line break?

To preserve a line break in a paragraph, insert a space followed by a plus sign ( + ) at the end of the line. This results in a visible line break (e.g., <br> ) following the line.

How do I add a line break in R?

To break a line in R Markdown and have it appear in your output, use two trailing spaces and then hit return .


2 Answers

How about this:

gsub('(.{1,90})(\\s|$)', '\\1\n', s) 

It will break string "s" into lines with maximum 90 chars (excluding the line break character "\n", but including inter-word spaces), unless there is a word itself exceeding 90 chars, then that word itself will occupy a whole line.

By the way, your function seems broken --- you should replace

lineLen <- 0 

with

lineLen <- wordLen[i] 
like image 174
xiechao Avatar answered Oct 04 '22 15:10

xiechao


For the sake of completeness, Karsten W.'s comment points at strwrap, which is the easiest function to remember:

strwrap("Lorem ipsum... you know the routine", width=10) 

and to match exactly the solution proposed in the question, the string has to be pasted afterwards:

paste(strwrap(s,90), collapse="\n") 

This post is deliberately made community wiki since the honor of finding the function isn't mine.

like image 21
3 revs, 3 users 62% Avatar answered Oct 04 '22 16:10

3 revs, 3 users 62%