Shorten a string to maximum N characters and only include full words - R

Viewed 42

I'm trying to shorten a string so that it is at most 50 characters long. However, only complete words should be included.

Example:

a <- "This is a very long string that should be a maximum of 50 characters and just full words"

expected result:

"This is a very long string that should be a"

Many Thanks.

1 Answers

You can use strwrap from base:

strwrap(a, 50)[1]
#[1] "This is a very long string that should be a"

or using stringi::stri_wrap:

stringi::stri_wrap(a, 50)[1]
#[1] "This is a very long string that should be a"

or using sub:

sub("(.{1,50})(\\s.*|$)", '\\1', a)
#[1] "This is a very long string that should be a"

sub("(.{1,50})(\\s.*|$)", '\\1', "Side by Side")
#[1] "Side by Side"
Related