Home > Software engineering >  How to separate values in a string only after the second space
How to separate values in a string only after the second space

Time:03-01

I have a string of names, for example:

st <- 'IKE IROEGBU NIMROD LEVI KYLE GIBSON CHAVAUGHN LEWIS BRYCE WASHINGSON'

and I want the output to be a vector like this:

c('IKE IROEGBU', 'NIMROD LEVI', 'KYLE GIBSON', 'CHAVAUGHN LEWIS', 'BRYCE WASHINGSON')

how can I do this?

CodePudding user response:

You can do:

st <- 'IKE IROEGBU NIMROD LEVI KYLE GIBSON CHAVAUGHN LEWIS BRYCE WASHINGSON'

c(stringr::str_match_all(st, "\\S \\s\\S ")[[1]])
#> [1] "IKE IROEGBU"      "NIMROD LEVI"      "KYLE GIBSON"      "CHAVAUGHN LEWIS" 
#> [5] "BRYCE WASHINGSON"

CodePudding user response:

An other, non-regex friendly way:

sst <- strsplit(st, " ")[[1]]
paste(sst[c(TRUE, FALSE)], sst[c(FALSE, TRUE)])

# [1] "IKE IROEGBU"      "NIMROD LEVI"      "KYLE GIBSON"      "CHAVAUGHN LEWIS"  "BRYCE WASHINGSON"

CodePudding user response:

Another way:

unlist(strsplit(st, " ")) -> names

i = 0
while (i < length(names) / 2) {
  
  print(
    paste0(names[1:2   i * 2], collapse = " ")
  )
  
  i = i   1
}

# [1] "IKE IROEGBU"
# [1] "NIMROD LEVI"
# [1] "KYLE GIBSON"
# [1] "CHAVAUGHN LEWIS"
# [1] "BRYCE WASHINGSON"
  •  Tags:  
  • r
  • Related