0

I've wrote code that does this:

text <- "abcdef"

substring(text, first = (1:(nchar(text)/2)) * 2 - 1, last = (1:(nchar(text)/2)) * 2)

Result:

"ab" "cd" "ef"

It works perfecty for small sized Strings but not for long ones.

Any suggestion, how I can do it faster?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Yuva
  • 95
  • 1
  • 1
  • 8

1 Answers1

2

Try trimws(gsub("(.{2})", "\\1 ", text)) and stringi::stri_sub(text, seq(1, stringi::stri_length(text), by = 2), length = 2)

nghauran
  • 6,648
  • 2
  • 20
  • 29
  • 1
    Would you please add your answer [here](https://stackoverflow.com/questions/11619616/how-to-split-a-string-into-substrings-of-a-given-length/11619681#11619681) so I can declare your answer as the accepted one? Otherwise, if people get here and see that it's a duplicate, they may not have a look at what you said as it's in the bottom of the windows – Yuva Feb 20 '18 at 11:24