Search code examples
rsorting

How to sort letters in a string?


Let's say I have a string s = "bcabca".

What is the simplest way to get "aabbcc" out of it, i.e., sort the letters in s?


Solution

  • Maybe not the most simple answer, but this will work:

    paste(sort(unlist(strsplit(s, ""))), collapse = "")
    

    Or modify the strReverse function that is defined in the help page for ?strsplit to suit our needs. We'll call it strSort:

    strSort <- function(x)
            sapply(lapply(strsplit(x, NULL), sort), paste, collapse="")