方法一:使用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字符串反转的资料请关注自学编程网其它相关文章!
- 本文固定链接: https://zxbcw.cn/post/194720/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)