首页 > 编程语言 > JAVA字符串反转的三种方法
2020
10-10

JAVA字符串反转的三种方法

方法一:使用StringBuilder

import java.util.Scanner;

public class StrReversal {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String str = scanner.nextLine();
    System.out.println(new StringBuilder(str).reverse());
  }
}

方法二:使用循环

import java.util.Scanner;

public class StrReversal {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String str = scanner.nextLine();
    char[] chars = str.toCharArray();
    String reverse = "";
    for (int i = chars.length - 1;i>=0;i--){
      reverse += chars[i];
    }
    System.out.println(reverse);
  }
}

方法三:考虑到String不可变,使用StringBuilder

import java.util.Scanner;

public class StrReversal {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String str = scanner.nextLine();
    char[] chars = str.toCharArray();
    StringBuilder reverse = new StringBuilder();
    for (int i = chars.length - 1;i>=0;i--){
      reverse.append(chars[i]);
    }
    System.out.println(reverse);
  }
}

以上就是JAVA字符串反转的三种方法的详细内容,更多关于JAVA字符串反转的资料请关注自学编程网其它相关文章!

编程技巧