简体   繁体   English

在长字符串中插入换行符

[英]Inserting line breaks in long strings

I'm writing a function to write automacilly tables in tex format. 我正在编写一个函数来编写tex格式的自动表。 One problem I'm having is with tables with long strings. 我遇到的一个问题是带有长字符串的表。 To solve this, I created a function that break long strings in more rows. 为了解决这个问题,我创建了一个在更多行中打破长字符串的函数。 My functions breaks in every space that have at leat len characters before (it doesn't break words). 我的函数在每个具有leat len字符的空间中都会中断(它不会破坏单词)。 I want change this rule to: Break in every space that the next space has at least len characters (in other words, I don't want 'substrings' with more than len characters, except that cases where a word has more than 10 characters). 我希望将此规则更改为:在下一个空格至少包含len字符的每个空格中断(换句话说,我不希望'子字符串'具有多个len字符,除了一个单词超过10个字符的情况)。

 quebra <- function(text, len=30) {
  trim <- function(x) gsub('^ *|(?<= ) | *$', '', x, perl=TRUE)
  quebrado <- strsplit(trim(paste(text)),paste0('(?<=.{',len,'}) '), perl=T)
  tam <- max(sapply(quebrado, length))
  out <- sapply(quebrado, function(x, tam) x[1:tam], tam=tam)
  out[is.na(out)] <- ''
  out
 }

Example: 例:

quebra('1234567890 123456789 123456789', 10) is returning: quebra('1234567890 123456789 123456789', 10)正在返回:

     [,1]                 
[1,] "1234567890"         
[2,] "123456789 123456789"

but I want: 但我想要:

     [,1]                 
[1,] "1234567890"         
[2,] "123456789"
[3,] "123456789"

I think this should work, but I could not adapt it to strsplit() format. 我认为应该可行,但我无法将其改编为strsplit()格式。

Don't reinvent the wheel. 不要重新发明轮子。 Just use strwrap . 只需使用strwrap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM