How to split a string every nth character?

Hi there!

I want to split a string onto a newline at a specified character. The reason is that I want to present it in a table, but the table cannot handle text wrapping when it is all one big string of text. Below is a demonstration of how strwrap and str_wrap don't really do what I need.

Any help / pointers appreciated! :slight_smile:

long_char <- paste(rep(LETTERS, 3), collapse = "")

long_char
#> [1] "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"

strwrap(long_char, width = 10, simplify = FALSE)
#> [[1]]
#> [1] "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
stringr::str_wrap(long_char, width = 10)
#> [1] "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"

# What I want - split (Say) every 10 characters
"ABCDEFGHIJ"
#> [1] "ABCDEFGHIJ"
"KLMNOPQRST"
#> [1] "KLMNOPQRST"
"UVWXYZABCD"
#> [1] "UVWXYZABCD"
"EFGHIJKLMN"
#> [1] "EFGHIJKLMN"
"OPQRSTUVWX"
#> [1] "OPQRSTUVWX"
"YZABCDEFGH"
#> [1] "YZABCDEFGH"
"IJKLMNOPQR"
#> [1] "IJKLMNOPQR"
"STUVWXYZ"
#> [1] "STUVWXYZ"

Created on 2020-09-09 by the reprex package (v0.3.0)

Note: I noticed a similar question for python on SO here, but couldn't find the equivalent in R.

I manually constructed the limits for the calls to str_sub() but it could be done programmatically.

library(stringr)

long_char <- paste(rep(LETTERS, 3), collapse = "")
StartVec <- 0:7 * 10 + 1
StopVec <- 1:8 * 10
str_sub(string = long_char, start = StartVec, end = StopVec)
#> [1] "ABCDEFGHIJ" "KLMNOPQRST" "UVWXYZABCD" "EFGHIJKLMN" "OPQRSTUVWX"
#> [6] "YZABCDEFGH" "IJKLMNOPQR" "STUVWXYZ"

Created on 2020-09-09 by the reprex package (v0.3.0)

1 Like

Oh, nice! Thank you so much! I'll have a go at wrapping this into a function and report back.

Really appreciate you taking the time.

PS.
Go Alto Clef!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.