1

Mytext is a long string delimited by blank space.

Mytextsample <- "aaaaabb cccdddd eee adssdada ooeoeo ososs ksdkd
ooeresso osososososos krrr dkdkkd odlcjs kdcmcmc ddddd dmssss"

I tried to add a new line every 10th blank using regular expressions How can I use a text replace function such as gsub or str_replace?

Paul
  • 2,877
  • 1
  • 12
  • 28
Hwang
  • 13
  • 2

1 Answers1

3

This solution first uses strsplit() your string into a vector at each space, split() it after every 10th item and uses paste0() to reassemble each level using sapply():

Mytextsample <- "aaaaabb cccdddd eee adssdada ooeoeo ososs ksdkd
  ooeresso osososososos krrr dkdkkd odlcjs kdcmcmc ddddd dmssss"

dat <- unlist(strsplit(Mytextsample, " ")) # unlist is here to convert to a vector
dat <- split(dat, ceiling(seq_along(dat)/10))

out <- sapply(dat, function(x) paste0(x, collapse = " "))
out
Paul
  • 2,877
  • 1
  • 12
  • 28
  • No problems, please [up-vote and accept](//https://stackoverflow.com/help/someone-answers) my answer if you think it is the best solution for your problem. – Paul Sep 20 '18 at 02:17