相关疑难解决方法(0)

在长字符串中插入换行符 - 自动换行

这是我写的一个函数,用于将长字符串分成不长于给定长度的行

strBreakInLines <- function(s, breakAt=90, prepend="") {
  words <- unlist(strsplit(s, " "))
  if (length(words)<2) return(s)
  wordLen <- unlist(Map(nchar, words))
  lineLen <- wordLen[1]
  res <- words[1]
  lineBreak <- paste("\n", prepend, sep="")
  for (i in 2:length(words)) {
    lineLen <- lineLen+wordLen[i]
    if (lineLen < breakAt) 
      res <- paste(res, words[i], sep=" ")
    else {
      res <- paste(res, words[i], sep=lineBreak)
      lineLen <- 0
    }
  }
  return(res)
}
Run Code Online (Sandbox Code Playgroud)

它适用于我遇到的问题; 但我想知道我是否可以在这里学到一些东西.是否有更短或更有效的解决方案,尤其是我可以摆脱for循环?

string r

22
推荐指数
4
解决办法
2万
查看次数

标签 统计

r ×1

string ×1