将字符串缩短到最多N个字符,并且只包含完整的单词-R

将字符串缩短到最多N个字符,并且只包含完整的单词-R,r,R,我正在尝试缩短一个字符串,使其长度最多为50个字符。但是,只应包括完整的单词 例如: a <- "This is a very long string that should be a maximum of 50 characters and just full words" 非常感谢。您可以从base使用strwrap: 或者使用stringi::stri_wrap: stringi::stri_wrap(a, 50)[1] #[1] "This is a

我正在尝试缩短一个字符串,使其长度最多为50个字符。但是,只应包括完整的单词

例如:

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

非常感谢。

您可以从base使用strwrap:

或者使用
stringi::stri_wrap

stringi::stri_wrap(a, 50)[1]
#[1] "This is a very long string that should be a"
或使用
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"

嗨,GKi,非常感谢你的快速回答。我会选择上一个解决方案,但它不适用于短字符串,短于50个字符。sub((.{1,50})\\s.*,'\\1',“并排”)-->“并排”如何修复?哦,对不起,我忘记了那个条件。请参阅更新。这可能有助于strsplit(a“”)
stringi::stri_wrap(a, 50)[1]
#[1] "This is a very long string that should be a"
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"