Insert line breaks in long string — word wrap

前端 未结 4 1630
情书的邮戳
情书的邮戳 2020-12-03 01:15

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=\"\") {
  w         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 01:51

    How about this:

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

    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
    

    with

    lineLen <- wordLen[i]
    

提交回复
热议问题