Search code examples
rstringrstringi

Insert vertical bar between each character of a string in R


How would I be able to insert a vertical bar in between every character of a string in R? For example, say I have a string "ABC123". How could I obtain the output to be "A|B|C|1|2|3"? If anyone could vectorize this idea for a vector of character strings, that would be great.


Solution

  • Here is an option using regex

    gsub("(?<=.)(?=.)", "|", "ABC123", perl = TRUE)
    #[1] "A|B|C|1|2|3"
    

    Or with more than one string

    mystrings <- c("ABC123", "PASDP")
    gsub("(?<=.)(?=.)", "|", mystrings, perl = TRUE)
    #[1] "A|B|C|1|2|3" "P|A|S|D|P"