Suppose I have a long string:
"XOVEWVJIEWNIGOIWENVOIWEWVWEW"
How do I split this to get every 5 characters followed by a space?
"XOVEW VJIEW NIGOI WENVO IWEWV WEW"
Note that the last one is shorter.
I can do a loop where I constantly count and build a new string character by character but surely there must be something better no?
You can try something like the following:
Output:
Now you can
paste
the resulting vector (withcollapse=' '
) to obtain a single string with spaces.You can also use a sub-string without a loop.
substring
is the vectorizedsubstr
Using regular expressions:
No *apply
stringi
solution:This extracts substrings just like in @Jilber answer, but
stri_sub
function is vectorized se we don't need to use *apply here.Using
sapply