Inversion of java strings using bit operation, value exchange, etc. - there are four methods

In this article, we will show you several ways to reverse the alphabetic order of String types in Java.

  • StringBuilder(str).reverse()
  • char[] loop and value exchange
  • byte loop and value exchange
  • apache-commons-lang3

For development, select StringBuilder (STR) Reverse() API. For the purpose of learning, we can study char[] and byte methods, which involve value exchange and shift operation techniques. These techniques are important for understanding StringBuilder (STR) The principles behind the reverse () API black box are very helpful.

1. StringBuilder(str).reverse()

In Java, we can use StringBuilder (STR) Reverse() reverses the string letters.

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());

    }
}

Output results

avaJ ni gnirtS a esreveR

2.char[]

First, we convert the string to a char array, loop through the char array one by one, and use the temp variable to exchange values.

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);
    }

}

The above algorithm requires five cycles (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
------------------------------------

3. Byte[] – StringBuilder(str).reverse(str)

The following code snippet is similar to StringBuilder (STR) Internal implementation of reverse() (except 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);
    }

}

The most confusing part is the shift right operator (length - 1) > > 1. What does that mean? Looking at the 8-bit examples below, can you find 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 = 3

For a number, the amount will be reduced by half and rounded for every one digit shift to the right. This (length - 1) > > 1 attempts to find the middle point of the string.

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

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;
}

The above algorithm 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}
------------------------------------

4. Apache commons-lang3

about Apache commons-lang3 Library, we can use stringutils Reverse reverses strings and stringutils Reversedeleted reverses the word.

pom.xml

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.10</version>
</dependency>
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

    }
}

Output results

avaJ dlroW olleH

Java World Hello

Looking at its source code, Apache-commons-lang3 actually 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();
  }

  //...
}

Welcome to my blog, there are many collections

  • Reprint of this article shall indicate the source (it must be connected, not just words): Letter brother blog.

If you think it is helpful to you, please help me to like and share! Your support is my inexhaustible creative power. In addition, the author has recently output the following fine content, looking forward to your attention.

Tags: Vue.js Apache

Posted by NDF on Mon, 30 May 2022 01:23:04 +0530