Sorting a String Alphabetically in Java – 在Java中按字母顺序对字符串进行排序

最后修改: 2018年 9月 1日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll show how to sort String alphabetically.

在本教程中,我们将展示如何按字母顺序对String排序。

There might be plenty of reason why we’d like to do it – one of them could be validation if two words are composed of the same characters set. That way, we’ll verify if they’re an anagram.

我们可能有很多理由要这样做–其中之一可能是验证两个词是否由相同的字符集组成。这样,我们就可以验证它们是否是一个变位词。

2. Sorting a String

2.对一个字符串进行排序

Internally, String uses an array of characters to operate on. Therefore, we can make use of the toCharArray() : char[] method, sort the array and create a new String based on the result:

在内部,String使用一个字符数组来进行操作。因此,我们可以使用toCharArray() : char[]方法,对数组进行排序,并根据结果创建一个新的String

@Test
void givenString_whenSort_thenSorted() {
    String abcd = "bdca";
    char[] chars = abcd.toCharArray();

    Arrays.sort(chars);
    String sorted = new String(chars);

    assertThat(sorted).isEqualTo("abcd");
}

In Java 8, we can leverage the Stream API to sort the String for us:

在Java 8中,我们可以利用Stream API来为我们排序String

@Test
void givenString_whenSortJava8_thenSorted() {
    String sorted = "bdca".chars()
      .sorted()
      .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
      .toString();

    assertThat(sorted).isEqualTo("abcd");
}

Here, we’re using the same algorithm as the first example, but sorting the char array using the Stream sorted() method.

这里,我们使用与第一个例子相同的算法,但使用Stream sorted()方法对char数组进行排序。

Notice, that characters are sorted by its ASCII codes, therefore, capital letters will always occur at the beginning. So, if we’d like to sort “abC” the result of sorting will be “Cab”.

注意,字符是按ASCII码排序的,因此,大写字母总是出现在开头。因此,如果我们想对 “abC “进行排序,排序的结果将是 “Cab”。

To solve it, we need to transform the string with toLowerCase() method. We’re going to do that in our Anagram validator example.

为了解决这个问题,我们需要toLowerCase()方法对字符串进行转换。我们将在我们的Anagram验证器例子中这样做。

3. Testing

3.测试

To test sorting, we’ll build the anagram validator. As mentioned an anagram occurs when two different words or sentences are compound of the same set of characters.

为了测试排序,我们将建立一个变位词验证器。如前所述,当两个不同的词或句子由同一组字符组成时,就会出现变位。

Let’s have a look at our AnagramValidator class:

让我们看一下我们的AnagramValidator类。

public class AnagramValidator {

    public static boolean isValid(String text, String anagram) {
        text = prepare(text);
        anagram = prepare(anagram);

        String sortedText = sort(text);
        String sortedAnagram = sort(anagram);

        return sortedText.equals(sortedAnagram);
    }

    private static String sort(String text) {
        char[] chars = prepare(text).toCharArray();

        Arrays.sort(chars);
        return new String(chars);
    }

    private static String prepare(String text) {
        return text.toLowerCase()
          .trim()
          .replaceAll("\\s+", "");
    }
}

Now, we’re going to make use of our sorting method and verify whether the anagram is valid:

现在,我们要利用我们的排序方法,验证这个变位词是否有效。

@Test
void givenValidAnagrams_whenSorted_thenEqual() {
    boolean isValidAnagram = AnagramValidator.isValid("Avida Dollars", "Salvador Dali");
        
    assertTrue(isValidAnagram);
}

4. Conclusion

4.总结

In this quick article, we’ve shown how the String might be sorted in alphabetical order in two ways. Also, we’ve implemented the anagram validator which made use of the string sorting method.

在这篇快速的文章中,我们已经展示了String如何以两种方式按字母顺序排序。此外,我们还实现了利用字符串排序方法的变位验证器。

As usual, the complete code is available on the GitHub project.

像往常一样,完整的代码可以在GitHub项目上获得。