在长字符串中插入换行符——自动换行 [英] Insert line breaks in long string -- word wrap

查看:75
本文介绍了在长字符串中插入换行符——自动换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here is a function I wrote to break a long string into lines not longer than a given length

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)
}

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

It works for the problem I had; but I wonder if I can learn something here. Is there a shorter or more efficient solution, especially can I get rid of the for loop?

推荐答案

这个怎么样:

gsub('(.{1,90})(\\s|$)', '\\1\n', s)

它会将字符串s"分成最多 90 个字符的行(不包括换行符\n",但包括词间空格),除非单词本身超过 90 个字符,否则该词本身将占据一整条线.

It will break string "s" into lines with maximum 90 chars (excluding the line break character "\n", but including inter-word spaces), unless there is a word itself exceeding 90 chars, then that word itself will occupy a whole line.

顺便说一下,你的功能好像坏了---你应该更换

By the way, your function seems broken --- you should replace

lineLen <- 0

lineLen <- wordLen[i]

这篇关于在长字符串中插入换行符——自动换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆