Regular expression – automatically inserts a newline in the long string

Is it possible to insert a newline character in such a string so that it can be adjusted automatically so as not to split 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 the post, but it separates the words and adds a newline after each string, I want to avoid

< /p>

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

The output I want is like this:

< p>

"I am a string" "So am I" "I am also a string but 
 way to long"

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=" " )
# [1] "I am a string" "So am I"
# [3] "I am also a string but way to long"

Is it possible to insert a newline character in such a string so that it can be adjusted automatically so as not to split 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 the post, but it separates the words and adds a newline after each string, I want to avoid

< /p>

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

The output I want is like this:

< p>

"I am a string" "So am I" "I am also a string but 
 way to long"

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=" " )
# [1] "I am a string" "So am I"
# [3] "I am also a string but way to long"

Leave a Comment

Your email address will not be published.