How to Reverse a String in Java – 如何在Java中反转一个字符串

最后修改: 2019年 7月 6日

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

1. Overview

1.概述

In this quick tutorial, we’re going to see how we can reverse a String in Java.

在这个快速教程中,我们将看到如何在Java中逆转一个字符串

We’ll start to do this processing using plain Java solutions. Next, we’ll have a look at the options that the third-party libraries like Apache Commons provide.

我们将开始使用普通的Java解决方案来进行这种处理。接下来,我们将看看Apache Commons等第三方库所提供的选项。

Furthermore, we’ll demonstrate how to reverse the order of words in a sentence.

此外,我们将演示如何颠倒句子中的单词顺序

2. A Traditional for Loop

2.一个传统的for循环

We know that strings are immutable in Java. An immutable object is an object whose internal state remains constant after it has been entirely created.

我们知道字符串在Java中是不可变的。不可变的对象是指在完全创建后,其内部状态保持不变的对象。

Therefore, we cannot reverse a String by modifying it. We need to create another String for this reason.

因此,我们不能通过修改一个String来逆转它。为此,我们需要创建另一个String

First, let’s see a basic example using a for loop. We’re going to iterate over the String input from the last to the first element and concatenate every character into a new String:

首先,让我们看一个使用for循环的基本例子。我们将从最后一个元素到第一个元素遍历String输入,并将每个字符串联成一个新的String

public String reverse(String input) {

    if (input == null) {
        return input;
    }

    String output = "";

    for (int i = input.length() - 1; i >= 0; i--) {
        output = output + input.charAt(i);
    }

    return output;
}

As we can see, we need to be careful at the corner cases and treat them separately.

正如我们所看到的,我们需要在角落的情况下小心谨慎,分别对待。

In order to better understand the example, we can build a unit test:

为了更好地理解这个例子,我们可以建立一个单元测试。

@Test
public void whenReverseIsCalled_ThenCorrectStringIsReturned() {
    String reversed = ReverseStringExamples.reverse("cat");
    String reversedNull = ReverseStringExamples.reverse(null);
    String reversedEmpty = ReverseStringExamples.reverse(StringUtils.EMPTY);

    assertEquals("tac", reversed);
    assertEquals(null, reversedNull);
    assertEquals(StringUtils.EMPTY, reversedEmpty);
}

3. A StringBuilder

3.一个StringBuilder

Java also offers some mechanisms like StringBuilder and StringBuffer that create a mutable sequence of characters. These objects have a reverse() method that helps us achieve the desired result.

Java还提供了一些机制,如StringBuilderStringBuffer,它们可以创建一个不可变的字符序列。这些对象有一个reverse()方法,可以帮助我们实现预期的结果。

Here, we need to create a StringBuilder from the String input and then call the reverse() method:

这里,我们需要从String输入创建一个StringBuilder,然后调用reverse()方法。

public String reverseUsingStringBuilder(String input) {
    if (input == null) {
        return null;
    }

    StringBuilder output = new StringBuilder(input).reverse();
    return output.toString();
}

4. Apache Commons

4.Apache Commons

Apache Commons is a popular Java library with a lot of utility classes including string manipulation.

Apache Commons是一个流行的Java库,有很多实用类,包括字符串操作。

As usual, to get started using Apache Commons, we first need to add the Maven dependency:

像往常一样,要开始使用Apache Commons,我们首先需要添加Maven依赖项

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

The StringUtils class is what we need here because it provides the reverse() method similar to StringBuilder.

StringUtils类是我们在这里需要的,因为它提供了类似于StringBuilderreverse()方法。

One advantage of using this library is that its utility methods perform null-safe operations. So, we don’t have to treat the edge cases separately.

使用这个库的一个好处是,其实用方法执行null安全操作。所以,我们不需要单独处理边缘情况。

Let’s create a method that fulfills our purpose and uses the StringUtils class:

让我们创建一个方法来实现我们的目的,并使用StringUtils类。

public String reverseUsingApacheCommons(String input) {
    return StringUtils.reverse(input);
}

Now, looking at these three methods, we can certainly say that the third one is the simplest and the least error-prone way to reverse a String.

现在,看看这三种方法,我们当然可以说,第三种方法是最简单和最不容易出错的逆转String的方法。

5. Reversing the Order of Words in a Sentence

5.颠倒句子中的字词顺序

Now, let’s assume we have a sentence with words separated by spaces and no punctuation marks. We need to reverse the order of words in this sentence.

现在,让我们假设我们有一个句子,其中的单词由空格分隔,没有标点符号。我们需要把这个句子中的词的顺序颠倒过来。

We can solve this problem in two steps: splitting the sentence by the space delimiter and then concatenating the words in reverse order.

我们可以分两步解决这个问题。通过空格分隔符分割句子,然后按相反的顺序串联单词。

First, we’ll show a classic approach. We’re going to use the String.split() method in order to fulfill the first part of our problem. Next, we’ll iterate backward through the resulting array and concatenate the words using a StringBuilder. Of course, we also need to add a space between these words:

首先,我们将展示一个经典的方法。我们将使用String.split() 方法来完成我们问题的第一部分。接下来,我们将向后迭代所得到的数组,并使用StringBuilder连接这些词。当然,我们还需要在这些词之间添加一个空格。

public String reverseTheOrderOfWords(String sentence) {
    if (sentence == null) {
        return null;
    }

    StringBuilder output = new StringBuilder();
    String[] words = sentence.split(" ");

    for (int i = words.length - 1; i >= 0; i--) {
        output.append(words[i]);
        output.append(" ");
    }

    return output.toString().trim();
}

Second, we’ll consider using the Apache Commons library. Once again, it helps us achieve a more readable and less error-prone code. We only need to call the StringUtils.reverseDelimited() method with the input sentence and the delimiter as arguments:

第二,我们将考虑使用Apache Commons库。再一次,它帮助我们实现了更可读、更少错误的代码。我们只需要调用StringUtils.reverseDelimited()方法,并将输入句子和分隔符作为参数。

public String reverseTheOrderOfWordsUsingApacheCommons(String sentence) {
    return StringUtils.reverseDelimited(sentence, ' ');
}

6. Conclusion

6.结论

In this tutorial, we’ve first looked at different ways of reversing a String in Java. We went through some examples using core Java, as well as using a popular third-party library like Apache Commons.

在本教程中,我们首先探讨了在Java中反转String的不同方法。我们经历了一些使用核心Java的例子,以及使用流行的第三方库,如Apache Commons。

Next, we’ve seen how to reverse the order of words in a sentence in two steps. These steps can also be helpful in achieving other permutations of a sentence.

接下来,我们已经看到了如何通过两个步骤颠倒句子中的单词顺序。这些步骤对实现一个句子的其他排列组合也有帮助。

As usual, all the code samples shown in this tutorial are available over on GitHub.

像往常一样,本教程中显示的所有代码样本都可以在GitHub上获得