Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

r - Insert line breaks in long string -- word wrap

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("
", 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)
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How about this:

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

It will break string "s" into lines with maximum 90 chars (excluding the line break character " ", 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

with

lineLen <- wordLen[i]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...