Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically inserting line breaks in long string

Tags:

regex

r

gsub

Is it possible to insert line breaks into a character string like this that automatically adjust so it don't split up words?

 nif <- as.character(c("I am a string", "So am I", 
     "I am also a string but way to long"))

I found this code in a post but it splits up words and also add a line break after each string which I would like to avoid

  gsub('(.{1,20})', '\\1\n',nif)

The output I am going for is this:

 "I am a string"    "So am I"     "I am also a string but \n way to long" 
like image 658
Einnor Avatar asked Nov 29 '22 16:11

Einnor


1 Answers

You can also use strwrap.

strwrap(nif, 20)
# [1] "I am a string"      "So am I"            "I am also a string"
# [4] "but way to long"   
sapply( strwrap(nif, 20, simplify=FALSE), paste, collapse="\n" )
# [1] "I am a string"                       "So am I"                            
# [3] "I am also a string\nbut way to long"
like image 181
Vincent Zoonekynd Avatar answered Dec 05 '22 11:12

Vincent Zoonekynd