Home Java javaTutorial 5 ways to achieve String reversal in Java

5 ways to achieve String reversal in Java

Jan 22, 2017 am 09:59 AM

Here is an introduction to how to implement String reversal in Java 5.

1. Array to achieve String reversal

//数组实现String反转
  public String reverseByArray(){
    if(str == null || str.length() == 1){
      return null;
    }
    char[] ch = str.toCharArray();//字符串转换成字符数组
    for(int i = 0 ; i < ch.length/2 ; i++){
      char temp = ch[i];
      ch[i] = ch[ch.length-i-1];
      ch[ch.length-i-1] = temp;
    }
    return new String(ch);
  }
Copy after login

2. Stack to implement String reversal

//用栈实现String反转
  public String reverseByStack(){
    if(str == null || str.length() == 1){
      return null;
    }
    Stack<Character> stack = new Stack<Character>();
    char[] ch = str.toCharArray();//字符串转换成字符数组
    for (char c : ch) {
      stack.push(c);//每个字符,推进栈
    }
    for (int i = 0; i < ch.length; i++) {
      ch[i] = stack.pop();//移除这个堆栈的顶部对象
    }
    return new String(ch);
  }
Copy after login


3. Reverse order traversal to implement String reversal Turn

//用逆序遍历实现String反转
 
  public String reverseBySort(){
    if(str == null || str.length() == 1){
      return null;
    }
    StringBuffer sb = new StringBuffer();
    for (int i = str.length() -1 ; i >= 0; i--) {
      sb.append(str.charAt(i));//使用StringBuffer从右往左拼接字符
    }
    return sb.toString();
  }
Copy after login

4. Bit operation to achieve String reversal

//使用位运算实现String反转
  public String reverseByBit() {
    if(str == null || str.length() == 1){
      return null;
    }
    char[] ch = str.toCharArray();//字符串转换成字符数组
    int len = str.length();
    for(int i= 0; i< len/ 2; i++) {
      ch[i]^= ch[len- 1- i];
      ch[len- 1- i]^= ch[i];
      ch[i]^= ch[len- 1- i];
    }
    return new String(ch);
  }
Copy after login

5. Recursion to achieve String reversal

//使用递归实现String反转
  public String reverseByRecursive(String str){
    if(str == null || str.length() == 0){
      return null;
    }
    if(str.length() == 1){
      return str;
    } else {
      //从下标为1开始截取字符串,在返回下标为0的字符
      return reverseByRecursive(str.substring(1)) + str.charAt(0);
    }
  }
Copy after login

6. Test

public class Test {
  public static void main(String[] args) {
    String s = "123456";
    Reverse r = new Reverse(s);
    System.out.println(r.reverseByArray());
    System.out.println(r.reverseByStack());
    System.out.println(r.reverseBySort());
    System.out.println(r.reverseByBit());
    System.out.println(r.reverseByRecursive(s));
     
  }
}
Copy after login

7. Results

5 ways to achieve String reversal in Java

8. All codes used for String reversal

public class Reverse {
  private String str = null;
   
  public Reverse(String str){
    this.str = str;
  }
   
  //数组实现String反转
  public String reverseByArray(){
    if(str == null || str.length() == 1){
      return null;
    }
    char[] ch = str.toCharArray();//字符串转换成字符数组
    for(int i = 0 ; i < ch.length/2 ; i++){
      char temp = ch[i];
      ch[i] = ch[ch.length-i-1];
      ch[ch.length-i-1] = temp;
    }
    return new String(ch);
  }
  //用栈实现String反转
  public String reverseByStack(){
    if(str == null || str.length() == 1){
      return null;
    }
    Stack<Character> stack = new Stack<Character>();
    char[] ch = str.toCharArray();//字符串转换成字符数组
    for (char c : ch) {
      stack.push(c);//每个字符,推进栈
    }
    for (int i = 0; i < ch.length; i++) {
      ch[i] = stack.pop();//移除这个堆栈的顶部对象
    }
    return new String(ch);
  }
  //用逆序遍历实现String反转
  public String reverseBySort(){
    if(str == null || str.length() == 1){
      return null;
    }
    StringBuffer sb = new StringBuffer();
    for (int i = str.length() -1 ; i >= 0; i--) {
      sb.append(str.charAt(i));//使用StringBuffer从右往左拼接字符
    }
    return sb.toString();
  }
  //使用位运算实现String反转
  public String reverseByBit() { 
    if(str == null || str.length() == 1){
      return null;
    }
    char[] ch = str.toCharArray();//字符串转换成字符数组
    int len = str.length(); 
    for(int i= 0; i< len/ 2; i++) { 
      ch[i]^= ch[len- 1- i]; 
      ch[len- 1- i]^= ch[i]; 
      ch[i]^= ch[len- 1- i]; 
    }
    return new String(ch);
  }
  //使用递归实现String反转
  public String reverseByRecursive(String str){
    if(str == null || str.length() == 0){
      return null;
    }
    if(str.length() == 1){
      return str;
    } else {
      //从下标为1开始截取字符串,在返回下标为0的字符
      return reverseByRecursive(str.substring(1)) + str.charAt(0);
    }
  }
}
Copy after login

The above 5 ways to achieve String reversal in Java are what I share with you. The entire content is here, I hope it can give everyone a reference, and I also hope everyone will support the PHP Chinese website.

For more articles related to 5 ways to achieve String reversal in Java, please pay attention to the PHP Chinese website!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles