是否可以将换行符插入这样的自动调整的字符串中,以免拆分单词?

 nif <- as.character(c("I am a string", "So am I",
     "I am also a string but way to long"))

我在一篇文章中发现了这个 code 但它拆分了单词并在每个字符串后添加了一个换行符,我想避免
  gsub('(.{1,20})', '\\1\n',nif)

我要的输出是这样的:
 "I am a string"    "So am I"     "I am also a string but \n way to long"

最佳答案

您也可以使用 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="\n" )
# [1] "I am a string"                       "So am I"
# [3] "I am also a string\nbut way to long"

关于regex - 自动在长字符串中插入换行符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16634139/

10-14 13:24