Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string on alternating index

Tags:

string

split

r

I have a string similar to "HLeelmloon" which is two words interweaved together. How can I separate this into two separate words, splitting on alternating letters?

I can use strsplit() and a for loop to allocate alternating letters to two new vectors and then join the list but this seems very long winded:

string <- "HLeelmloon"
split<-el(strsplit(string,''))

> split
[1] "H" "L" "e" "e" "l" "m" "l" "o" "o" "n"

word1<-c()
word2<-c()
for(i in 1:length(split)){
  if(i %% 2 == 1){
    word1<-append(word1, split[i])
  } else {
    word2<-append(word2, split[i])
  }
}

word1 = paste0(word1, collapse = '')
word2 = paste0(word2, collapse = '')

> word1
[1] "Hello"
> word2
[1] "Lemon"

My issue is it's not very elegant, and it doesn't upscale well if I want to split the string into N different words. Is there a better way to do this?

like image 769
Andrew Haynes Avatar asked May 14 '26 06:05

Andrew Haynes


2 Answers

You could use gsub to capture alternating characters into the same group:

gsub("(.)(.)?", "\\1", string)
#[1] "Hello"
gsub("(.)(.)?", "\\2", string)
#[1] "Lemon"
like image 137
Mike H. Avatar answered May 15 '26 21:05

Mike H.


You can do it by using TRUE and FALSE for indexing, i.e.

v1 = strsplit(string, '')[[1]]

paste(v1[c(TRUE, FALSE)], collapse = '')
#[1] "Hello"

paste(v1[c(FALSE, TRUE)], collapse = '')
#[1] "Lemon"
like image 33
Sotos Avatar answered May 15 '26 22:05

Sotos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!