[英]Shorten a string to maximum N characters and only include full words - R
我正在嘗試縮短一個字符串,使其長度最多為 50 個字符。 但是,應該只包含完整的單詞。
例子:
a <- "This is a very long string that should be a maximum of 50 characters and just full words"
預期結果:
"This is a very long string that should be a"
非常感謝。
您可以使用來自base的strwrap
:
strwrap(a, 50)[1]
#[1] "This is a very long string that should be a"
或使用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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.