Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort letters in a string?

Tags:

sorting

r

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?

like image 336
Leo Avatar asked May 05 '11 22:05

Leo


People also ask

How do you sort data in a string?

The main logic is to toCharArray() method of the String class over the input string to create a character array for the input string. Now use Arrays. sort(char c[]) method to sort character array. Use the String class constructor to create a sorted string from a char array.

How do you sort letters in a string alphabetically in Python?

Use sorted() and str. join() to sort a string alphabetically in Python. Another alternative is to use reduce() method. It applies a join function on the sorted list using the '+' operator.

Can I sort a string in Python?

Sort a Python String with SortedPython comes with a function, sorted() , built-in. This function takes an iterable item and sorts the elements by a given key. The default value for this key is None , which compares the elements directly. The function returns a list of all the sorted elements.


3 Answers

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="")
like image 173
Chase Avatar answered Oct 20 '22 23:10

Chase


Here's a variant of Chase's solution that handles a vector of strings and keeps the original strings as names. ...and I get a chance to promote the use of vapply over sapply :-)

> x=c('hello', 'world', NA, 'a whole sentence')
> vapply(x, function(xi) paste(sort(strsplit(xi, NULL)[[1]]), collapse=''), '')
             hello              world               <NA>   a whole sentence 
           "ehllo"            "dlorw"                 "" "  aceeeehlnnostw" 
like image 18
Tommy Avatar answered Oct 20 '22 21:10

Tommy


It might be good to mention the stringi package for this problem. It's stri_order and stri_sort functions are very efficient, testing at half the time of the base R method mentioned above.

library(stringi)
## generate 10k random strings of 100 characters each
str <- stri_rand_strings(1e4, 100)
## helper function for vapply()
striHelper <- function(x) stri_c(x[stri_order(x)], collapse = "")
## timings
system.time({
  v1 <- vapply(stri_split_boundaries(str, type = "character"), striHelper, "")
})
#    user  system elapsed 
#   0.747   0.000   0.743 

system.time({
  v2 <- sapply(lapply(strsplit(str, NULL), sort), paste, collapse="")
})
#    user  system elapsed 
#   2.077   0.000   2.068 

identical(v1, v2)
# [1] TRUE
like image 8
Rich Scriven Avatar answered Oct 20 '22 21:10

Rich Scriven