In this article, we’ll show you several ways to reverse alphabetical order for strings in Java.

  • StringBuilder(str).reverse()
  • char[]Loops and value swaps
  • byteLoops and value swaps
  • apache-commons-lang3

For development purposes, select the StringBuilder(STR).reverse()API. For learning purposes, we can look at char[] and byte methods, which involve value swaps and shift operations that are useful for understanding the principles behind the StringBuilder(STR).reverse()API black box.

1. StringBuilder(str).reverse()

In Java, we can use StringBuilder(STR).reverse() to reverse the letters of a string.

public class ReverseString1 { public static void main(String[] args) { String str = "Reverse a String in Java"; StringBuilder sb = new StringBuilder(str).reverse(); System.out.println(sb.toString()); }}Copy the code

The output

avaJ ni gnirtS a esreveRCopy the code

2.char[]

First, we convert the string to a CHAR array and loop through the char arrays one by one, swapping values using the temp variable.

public class ReverseString2 {

    public static void main(String[] args) {

        String str = "Hello World";
        System.out.println(reverse(str));         //  dlroW olleH

    }

    public static String reverse(String input) {

        if (input == null || input.length() < 0)
            throw new IllegalArgumentException("Please provide an input!");

        char[] result = input.toCharArray();

        int startIndex = 0;
        int endIndex = result.length - 1;
        char temp;

        for (; endIndex > startIndex; startIndex++, endIndex--) {
            temp = result[startIndex];
            result[startIndex] = result[endIndex];
            result[endIndex] = temp;
        }

        return new String(result);
    }

}Copy the code

The algorithm above requires 5 loops (length / 2) to reverse the string “Hello World”.

------------------------------------
H  e  l  l  o     W  o  r  l  d
------------------------------------
0  1  2  3  4  5  6  7  8  9  10
------------------------------------

Loop #1 - Swap index 0 <-> index 10
------------------------------------
{d}  e  l  l  o     W  o  r  l  {H}
------------------------------------
{0}  1  2  3  4  5  6  7  8  9  {10}
------------------------------------

Loop #2 - Swap index 1 <-> index 9
------------------------------------
d  {l}  l  l  o     W  o  r  {e}  H
------------------------------------
0  {1}  2  3  4  5  6  7  8  {9}  10
------------------------------------

Loop #3 - Swap index 2 <-> index 8
------------------------------------
d  l  {r}  l  o     W  o  {l}  e  H
------------------------------------
0  1  {2}  3  4  5  6  7  {8}  9  10
------------------------------------

Loop #4 - Swap index 3 <-> index 7
------------------------------------
d  l  r  {o}  o     W  {l}  l  e  H
------------------------------------
0  1  2  {3}  4  5  6  {7}  8  9  10
------------------------------------

Loop #5 - Swap index 4 <-> index 6
------------------------------------
d  l  r  o  {W}     {o}  l  l  e  H
------------------------------------
0  1  2  3  {4}  5  {6}  7  8  9  10
------------------------------------Copy the code

3. Byte [] - StringBuilder (STR). Reverse (STR)

The following code snippet is similar to the internal implementation of StringBuilder(STR).reverse() (except for the UTF16 content).

import java.nio.charset.StandardCharsets;

public class ReverseString3 {

    public static void main(String[] args) {

        String str = "Hello World";
        System.out.println(reverse(str));

    }

    public static String reverse(String input) {

        if (input == null || input.length() < 0)
            throw new IllegalArgumentException("Please provide an input!");

        byte[] val = input.getBytes(StandardCharsets.UTF_8);
        int length = val.length - 1;

        for (int start = (length - 1) >> 1; start >= 0; start--) {
            int end = length - start;
            byte temp = val[start];
            val[start] = val[end];
            val[end] = temp;

            // debugging
            //System.out.println(String.format("start=%s, end=%s", start, end));
        }

        return new String(val);
    }

}Copy the code

The most confusing part is the right shift operator (Length-1) >> 1. What does that mean? Looking at the 8-bit example below, can you see a pattern?

System.out.println(10>>1); // 10 -> 5 0000 1010 = 10 0000 0101|0 = 10 >> 1 = 5 System.out.println(4>>1); // 4 -> 2 0000 0100 = 4 0000 0010|0 = 4 >> 1 = 2 System.out.println(100>>1); // 100 -> 50 0110 0100 = 100 00110 010|0 = 100 >> 1 = 50 System.out.println(7>>1); / / 7 - > 3, 0000, 0111 = 7 0000 0011 | 1 = 7 > > 1 = 3Copy the code

For a number, the amount is reduced by half and rounded for every 1 bit to the right. This (length-1) >> 1 tries to find the middle point of the string.

number >> 1 = round_down(number/2) or Math.flooa(number/2)Copy the code

Value exchange starts internally and then extends externally.

for (int start = (length - 1) >> 1; start >= 0; start--) {
    int end = length - start;
    byte temp = val[start];
    val[start] = val[end];
    val[end] = temp;
}Copy the code

The algorithm above is shown as follows:

------------------------------------ H e l l o W o r l d ------------------------------------ 0 1 2 3 4 5 6 7 8 9 10 ------------------------------------ Loop #1 - Swap index 4 <-> index 6 ------------------------------------ H e l l {W}  {o} o r l d ------------------------------------ 0 1 2 3 {4} 5 {6} 7 8 9 10 ------------------------------------ Loop #2 - Swap index 3 <-> index 7 ------------------------------------ H e l {o} W o {l} r l d ------------------------------------ 0 1 2 {3} 4 5 6 {7} 8 9 10 ------------------------------------ Loop #3 - Swap index 2 <-> index 8 ------------------------------------ H e {r} o W o l {l} l d ------------------------------------ 0 1 {2} 3 4 5 6 7 {8} 9 10 ------------------------------------ Loop #4 - Swap index 1 <-> index 9 ------------------------------------ H {l} r o W o l l {e} d ------------------------------------ 0 {1} 2 3 4 5 6 7 8 {9} 10 ------------------------------------ Loop #5 - Swap index 0 <-> index 10 ------------------------------------ {d}  l r o W o l l e {H} ------------------------------------ {0} 1 2 3 4 5 6 7 8 9 {10} ------------------------------------Copy the code

4. Apache commons-lang3

For Apache Commons – lang3 library, we can use the StringUtils. Reverse reverse string and StringUtils reverseDelimited inversion of words.

pom.xml

Mons < dependency > < groupId > org.apache.com < / groupId > < artifactId > Commons - lang3 < / artifactId > < version > 3.10 < / version > </dependency>Copy the code
import org.apache.commons.lang3.StringUtils;

public class ReverseString3 {

    public static void main(String[] args) {

        System.out.println(StringUtils.reverse("Hello World Java"));                // reverse string

        System.out.println(StringUtils.reverseDelimited("Hello World Java", ' '));  // reverse words

    }
}Copy the code

The output

avaJ dlroW olleH

Java World HelloCopy the code

Looking at the source code, apache-Commons-lang3 uses new StringBuilder(STR).reverse() to reverse the string.

package org.apache.commons.lang3; public class StringUtils { public static String reverse(final String str) { if (str == null) { return null; } return new StringBuilder(str).reverse().toString(); } / /... }Copy the code

Welcome to my blog, where there are many fine collections

  • This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.

Feel helpful to you, help me like, share! Your support is my inexhaustible creative power! . In addition, the author recently a period of time output as follows boutique content, looking forward to your attention.

  • Spring Boot2.0 by Hand
  • Spring Security- JWT-OAUTH2
  • RBAC Authority Management System for Actual Combat Front-end and Back-end Separation
  • “Actual SpringCloud Micro-service from Bronze to King”
  • VUE Series