JAVA字符串反转 JAVA字符串反转的三种方法
深浅无解 人气:0想了解JAVA字符串反转的三种方法的相关内容吗,深浅无解在本文为您仔细讲解JAVA字符串反转的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,字符串,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); } }
加载全部内容