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?
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.
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.
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.
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="")
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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With