<img src="https://s2.51cto.com/images/blog/202306/02140215_647985e7564a969728.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_30,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=" alt="StringBuilder反向API">

java 字节颠倒 java怎么反转字符串_Java


在本文中,我们将向您展示几种在Java中反转String的方法。

StringBuilder(str).reverse()char[]

  • 循环和值交换。

byte

  • 循环和值交换。

commons-lang3StringBuilder(str).reverse()char[]byte方法,它涉及值交换和按位移位技术,这些技术对于理解反向API黑匣子背后的情况非常有用。

1. StringBuilder(str).reverse()

StringBuilder(str).reverse()来反转字符串。

ReverseString1.java


package com.mkyong.crypto.bytes;

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

    }

}

输出量


Terminal


avaJ ni gnirtS a esreveR


2.字符[]

首先,我们将字符串转换为char数组,并逐个循环char数组,并使用temp变量交换值。


ReverseString2.java


package com.mkyong.utils;

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

}

上面的算法需要5个循环(长度/ 2)来反转字符串“ 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()

StringBuilder(str).reverse()来反转字符串(UTF16内容除外)。

ReverseString3.java


package com.mkyong.crypto.bytes;

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

}

(length - 1) >> 1

查看下面的8位示例,您可以找到模式吗?

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

(length - 1) >> 1试图找出字符串的中间点。

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

价值交换从内部开始,然后扩展到外部。

for (int start = (length - 1) >> 1; start >= 0; start--) {
      int end = length - start;
      byte temp = val[start];
      val[start] = val[end];
      val[end] = temp;
  }
------------------------------------
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

对于Apache commons-lang3库,我们可以使用StringUtils.reverse来反转字符串,并使用StringUtils.reverseDelimited来反转单词。

pom.xml


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


ReverseString3.java


package com.mkyong.utils;

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

    }
}

输出量


Terminal


avaJ dlroW olleH

Java World Hello

commons-lang3使用new StringBuilder(str).reverse()来反转字符串。

StringUtils.java


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

  //...
}

参考文献

标签: 算法 移位 逐位 Java 反向字符串



翻译自: https://mkyong.com/java/how-to-reverse-a-string-in-java/