Home > front end >  How can I concatenate these strings back together?
How can I concatenate these strings back together?

Time:03-09

I would like to split a string into its elements and then paste them together again. However no matter what I tried, it doesn`t work.

Here are two things I've tried:

'hello' %>% strsplit('') %>% paste0()

output: "c(\"h\", \"e\", \"l\", \"l\", \"o\")"

'hello' %>% strsplit('') %>% unlist() %>% paste0()

output: "h" "e" "l" "l" "o"

I would simply like to get my 'hello' back.

CodePudding user response:

You can use paste but you have to specify the collapse argument.

'hello' %>% strsplit('') %>% unlist() %>% paste(collapse = "")

Alternatively you can use str_c from the stringr library:

'hello' %>% strsplit('') %>% unlist() %>% stringr::str_c(collapse = "")

CodePudding user response:

Another solution is to use stringr::str_flatten which explicitly does what you want:

library(stringr)
'hello' %>% 
  strsplit('') %>% 
  unlist() %>% 
  str_flatten()

# [1] "hello"

To avoid unlist, you can use stringr::str_split with simplify = TRUE:

'hello' %>% 
  str_split('', simplify = T) %>% 
  str_flatten()

CodePudding user response:

We can try unlist as.list do.call along with paste0 like below

"hello" %>%
  strsplit("") %>%
  unlist() %>%
  as.list() %>%
  do.call(paste0, .)
  • Related