7

如何使用取自另一个字符串的字母顺序创建一个字符串?

假设我有这样的东西

String theWord = "Hello World";

如何计算新字符串以使其看起来像“

德鲁洛

这是 theWord,但按字母顺序逐个字符排序。

提前致谢

4

8 回答 8

30
char[] chars = theWord.toCharArray();
Arrays.sort(chars);
String newWord = new String(chars);
于 2011-06-07T14:20:24.970 回答
10

Arrays.sort()&toCharArray()

于 2011-06-07T14:19:30.053 回答
4

同意,我偷了解决方案。但显然,去除空格并使所有内容小写也很重要:

char[] array = theWord.replaceAll("\\s+", "").toLowerCase().toCharArray();
Arrays.sort(array);
System.out.println(new String(array));
于 2011-06-07T14:22:42.467 回答
2

上述解决方案都不是特定于语言环境的,因此我提出了这个解决方案,它效率不高,但效果很好..

public static String localeSpecificStringSort(String str, Locale locale) {

        String[] strArr = new String[str.length()];

        for(int i=0;i<str.length();i++){
            strArr[i] =  str.substring(i,i+1);
        }
        Collator collator = Collator.getInstance(locale);
        Arrays.sort(strArr, collator);
        StringBuffer strBuf = new StringBuffer();
        for (String string : strArr) {
            strBuf.append(string);
        }
        return strBuf.toString();
    }
于 2011-06-07T14:48:56.327 回答
1
char[] arr = new char[theWord.length()];
for(int i=0;i<theWord.length;i++)
{
    arr[i]=theWord.charAt(i);
}
for(int i=0;i<theWord.length();i++)
  for(int j=0;j<theWord.length();j++)
{
    char temp = arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
}
int size=theWord.length();
theWord="";
for(int i=0;i<size;i++)
{
    theWord+=arr[i];
}
于 2012-06-14T10:51:44.673 回答
0
import java.util.Arrays;
import java.util.Scanner;

// re arrange alphabets in order
public class RearrangeAlphabets {

    @SuppressWarnings("resource")
    public static void main(String[] args) {

        String theWord;
        Scanner in = new Scanner(System.in);

        System.out.println("Enter a string to rearrange: \n");

        theWord = in.nextLine();
        int length = theWord.length();
        System.out.println("Length of string: "+length);
        char[] chars=theWord.toCharArray();
        Arrays.sort(chars);
        String newWord=new String(chars);

        System.out.println("The Re-Arranged word : "+newWord);

    }

}
于 2016-09-25T10:10:17.683 回答
0
char[]  chars2  = b.toLowerCase().toCharArray();
Arrays.sort(chars1);
String  Ns1   = new String(chars1);
于 2016-10-31T05:01:26.320 回答
0

所有解决方案都是 O(nlogn),因为它们正在对数组进行排序。相反,我们可以使用 array[26] 并在 O(n) 中执行此操作。将其转换为小写并删除 O(n), int[] ar=new int[26]; for(char c:s.toCharArray()) ar[c-'a']++; 然后形成所需的字符串 O(n)。

于 2018-10-15T13:57:03.007 回答