Java 按字母顺序对字符串中的字符进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30199304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:18:42  来源:igfitidea点击:

Sorting characters alphabetically in a String

javaarraysstringsortingchar

提问by

Could smb please explaing the process of sorting characters of Stringalphabetically? For example, if I have String "hello"the output should be "ehllo"but my code is doing it wrong.

请smb解释一下String按字母顺序排列字符的过程吗?例如,如果我有String "hello"输出应该是"ehllo"但我的代码做错了。

public static void main(String[] args)
    {
        String result = "";
        Scanner kbd = new Scanner(System.in);
        String input = kbd.nextLine();

        for(int i = 1; i < input.length(); i++)
        {
            if(input.charAt(i-1) < input.charAt(i))
                result += input.charAt(i-1);
            //else 
            //  result += input.charAt(i);
        }
        System.out.println(result);
    }


}

采纳答案by Razib

You may do the following thing -

你可以做以下事情——

1.Convert your String to char[]array.
2.Using Arrays.sort()sort your char array

1.将您的字符串转换为char[]数组。
2.使用Arrays.sort()排序你的字符数组

Code snippet:

代码片段:

String input = "hello";
char[] charArray = input.toCharArray();
Arrays.sort(charArray);
String sortedString = new String(charArray);
System.out.println(sortedString);  

Or if you want to sort the array using for loop (for learning purpose) you may use (But I think the first one is best option ) the following code snippet-

或者,如果您想使用 for 循环(出于学习目的)对数组进行排序,您可以使用(但我认为第一个是最好的选择)以下代码片段-

input="hello";
char[] charArray = input.toCharArray();
length = charArray.length();

for(int i=0;i<length;i++){
   for(int j=i+1;j<length;j++){
      if (charArray[j] < charArray[i]) {
          char temp = charArray[i];
          charArray[i]=arr[j];
          charArray[j]=temp;
      }
   }
}

回答by fsalazar_sch

In your for bucle is starting at 1, should be start at zero

在你的 for bucle 从 1 开始,应该从零开始

for(int i = 0; i < input.length(); i++){...}

回答by GreySage

Sorting as a task has a lower bound of O(n*logn), with n being the number of elements to sort. What this means is that if you are using a single loop with simple operations, it will not be guaranteed to sort correctly. A key element in sorting is deciding what you are sorting by. In this case its alphabetically, which, if you convert each character to a char, equates to sorting in ascending order, since a char is actually just a number that the machine maps to the character, with 'a' < 'b'. The only gotcha to look out for is mixed case, since 'z' < 'A'. To get around, this, you can use str.tolower(). I'd recommend you look up some basic sorting algorithms too.

作为任务排序的下限为 O(n*logn),n 是要排序的元素数。这意味着如果您使用具有简单操作的单个循环,则不能保证正确排序。排序中的一个关键要素是决定您排序的依据。在这种情况下,它按字母顺序排列,如果将每个字符转换为字符,则相当于按升序排序,因为字符实际上只是机器映射到字符的数字,其中 'a' < 'b'。唯一需要注意的问题是大小写混合,因为 'z' < 'A'。为了解决这个问题,您可以使用str.tolower(). 我建议您也查找一些基本的排序算法。

回答by rashedcs

Procedure :

程序 :

  1. At first convert the string to char array

  2. Then sort the array of character

  3. Convert the character array to string

  4. Print the string

  1. 首先将字符串转换为字符数组

  2. 然后对字符数组进行排序

  3. 将字符数组转换为字符串

  4. 打印字符串



Code snippet:

代码片段:

 String input = "world";
 char[] arr = input.toCharArray();
 Arrays.sort(arr);
 String sorted = new String(arr);
 System.out.println(sorted);

回答by bpjoshi

You can sort a String in Java 8 using Stream as below:

您可以使用 Stream 对 Java 8 中的字符串进行排序,如下所示:

String sortedString =
    Stream.of("hello".split(""))
    .sorted()
    .collect(Collectors.joining());

回答by bpjoshi

You can do this using Arrays.sort, if you put the characters into an array first.

Arrays.sort如果先将字符放入数组,则可以使用,来执行此操作。

Character[] chars = new Character[str.length()];

for (int i = 0; i < chars.length; i++)
    chars[i] = str.charAt(i);

// sort the array
Arrays.sort(chars, new Comparator<Character>() {
    public int compare(Character c1, Character c2) {
        int cmp = Character.compare(
            Character.toLowerCase(c1.charValue()),
            Character.toLowerCase(c2.charValue())
        );
        if (cmp != 0) return cmp;
        return Character.compare(c1.charValue(), c2.charValue());
    }
});

Now build a string from it using StringBuilder.

现在使用StringBuilder.

回答by bpjoshi

Most basic and brute force approach using the two for loop: It sort the string but with the cost of O(n^2) time complexity.

使用两个 for 循环的最基本和蛮力方法:它对字符串进行排序,但时间复杂度为 O(n^2)。

public void stringSort(String str){
        char[] token = str.toCharArray();
        for(int i = 0; i<token.length; i++){
            for(int j = i+1; j<token.length; j++){
                if(token[i] > token[j]){
                    char temp = token[i];
                    token[i] = token[j];
                    token[j] = temp;
                }
            }
        }
        System.out.print(Arrays.toString(token));
    }

回答by Tarun Jadhav

public class SortCharcterInString {

公共类 SortCharcterInString {

public static void main(String[] args) {
    String str = "Hello World";
    char[] arr;
    List<Character> L = new ArrayList<Character>();
    for (int i = 0; i < str.length(); i++) {
        arr = str.toLowerCase().toCharArray();
        L.add(arr[i]);

    }
    Collections.sort(L);
    str = L.toString();
    str = str.replaceAll("\[", "").replaceAll("\]", "")
            .replaceAll("[,]", "").replaceAll(" ", "");
    System.out.println(str);

}