1

I need to locate the first space following each 20 characters in a string and insert a new line instead of this space. I´m using R and the stringr package. So far I managed to add a new line instead of each space using this code:

gsub(" ", "\n", "My very long and very annoying string")

"My\nvery\nlong\nand\nvery\nannoying\nstring"

But I need to do this only for the first space after the 20th, 40th, 60th etc. character. The result should look like this (because very constains the 20th character):

"My very long and very\nannoying string"

How can I solve this?

Ali Khaki
  • 1,184
  • 1
  • 13
  • 24
jvin
  • 13
  • 3
  • 1
    See the 'wrap_text' function in Martin's answer here: https://stackoverflow.com/questions/49756457/wrap-long-text-in-a-text-box/49756990#49756990 – Dave2e Nov 06 '18 at 19:46

1 Answers1

0

Let's first take a little longer string:

txt <- "My very long long long long and very annoying string"

Then we may do the following

aux <- str_locate_all(txt, " ")[[1]]
pos <- aux[which(diff(aux[, 1] %/% 20) == 1) + 1, 1]
for(p in pos)
  substr(txt, p, p) <- "\n"

cat(txt)
# My very long long long
# long and very annoying
# string
Julius Vainora
  • 47,421
  • 9
  • 90
  • 102