1. 案例演示:
1 package cn.itcast_07; 2 3 import java.util.Scanner; 4 5 /* 6 * 把字符串反转 7 */ 8 public class StringBufferTest3 { 9 public static void main(String[] args) { 10 // 键盘录入数据 11 Scanner sc = new Scanner(System.in); 12 System.out.println("请输入数据:"); 13 String s = sc.nextLine(); 14 15 // 方式1:用String做拼接 16 String s1 = myReverse(s); 17 System.out.println("s1:" + s1); 18 // 方式2:用StringBuffer的reverse()功能 19 String s2 = myReverse2(s); 20 System.out.println("s2:" + s2); 21 } 22 23 // 用StringBuffer的reverse()功能 24 public static String myReverse2(String s) { 25 // StringBuffer sb = new StringBuffer(); 26 // sb.append(s); 27 28 // StringBuffer sb = new StringBuffer(s); 29 // sb.reverse(); 30 // return sb.toString(); 31 32 // 简易版 33 return new StringBuffer(s).reverse().toString(); 34 } 35 36 // 用String做拼接 37 public static String myReverse(String s) { 38 String result = ""; 39 40 char[] chs = s.toCharArray(); 41 for (int x = chs.length - 1; x >= 0; x--) { 42 // char ch = chs[x]; 43 // result += ch; 44 result += chs[x]; 45 } 46 47 return result; 48 } 49 }
运行结果: