如何对字符串中的字母进行排序?

如何对字符串中的字母进行排序?

问题描述:

假设我有一个字符串s = "bcabca".

从中提取"aabbcc"的最简单方法是什么,即对s中的字母进行排序?

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

也许不是最简单的答案,但这会起作用:

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

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

或修改帮助页面中为?strsplit定义的strReverse功能,以适应我们的需求.我们将其称为strSort:

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="")