Einnor
Einnor

Reputation: 239

Automatically inserting line breaks in long string

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" 

Upvotes: 6

Views: 2574

Answers (2)

Vincent Zoonekynd
Vincent Zoonekynd

Reputation: 32361

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"

Upvotes: 20

agstudy
agstudy

Reputation: 121578

You can find the first space after some number of letters and replace it with \n

For example something like this

 gsub('(.{18})\\s(.*)', '\\1\n\\2',nif)

[1] "I am a string"                       "So am I"                            
    "I am also a string\nbut way to long"

Upvotes: 6

Related Questions