package cn.com; import java.util.Scanner; public class stringFlip2 { public static void main(String[] ages){ Scanner s = new Scanner(System.in); System.out.println("输入一个数,放入字符串中"); if (s.hasNextLine()) { String A = s.nextLine(); System.out.println("输入的数据为:" + A); System.out.println("--------------"); for(int i = A.length() -1;i>=0;i--){ System.out.println(A.charAt(i)); } System.out.println("------------"); System.out.println("变换前:" + A); System.out.println("变换后:" + reverse1(A)); } s.close(); } //第1种方法 // StringBuffer 将字符串翻转 public static String reverse1(String Str) { return new StringBuilder(Str).reverse().toString(); } }
//2.第二种方法 public static String reverse1(String str) { char[] chars = str.toCharArray(); String reverse = ""; for (int i = chars.length - 1; i >= 0; i--) { reverse += chars[i]; } return reverse; }
//第3种方法 public static String reverse1(String str) { String reverse = ""; int length = str.length(); for (int i = 0; i < length; i++) { reverse = str.charAt(i) + reverse; } return reverse; }