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.
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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.