Split a string on alternating index

  • A+
Category:Languages

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?


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

gsub("(.)(.)?", "//1", string) #[1] "Hello" gsub("(.)(.)?", "//2", string) #[1] "Lemon" 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: