Java如何反转字符串,单词或句子?

package org.nhooo.example.commons.lang;

import org.apache.commons.lang3.StringUtils;

public class StringReverseDemo {
    public static void main(String[] args) {
        // 我们这里有一个原始字符串,我们需要将其反转。
        String words = "The quick brown fox jumps over the lazy dog";

        // 使用StringUtils.reverse,我们可以逐个字母地反转字符串。
        String reversed = StringUtils.reverse(words);

        // 现在我们想反转每个单词,我们可以使用
        // 使用StringUtils.reverseDelimited()方法来执行此操作。
        String delimitedReverse = StringUtils.reverseDelimited(words, ' ');

        // 打印结果
        System.out.println("Original: " + words);
        System.out.println("Reversed: " + reversed);
        System.out.println("Delimited Reverse: " + delimitedReverse);
    }
}

结果如下:

Original: The quick brown fox jumps over the lazy dog
Reversed: god yzal eht revo spmuj xof nworb kciuq ehT
Delimited Reverse: dog lazy the over jumps fox brown quick The

Maven依赖

<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

Maven中央