1.最简单直接的方法 :StringBuilder StringBuffer reverse
String str = "123456789qwertyuiop"; StringBuffer sBuffer = new StringBuffer(str); StringBuilder sBuilder =new StringBuilder(str); System.out.println(sBuffer.reverse()); System.out.println(sBuilder.reverse());
2.charAt()
/** * 该方法是通过charAt()方法获得每一个char的字符,i=0时获得第一个字符a然后赋值给reverse * 此时reverse="a";i=1时获得第二个字符b然后加上reverse再赋值给reverse,此时reverse="ba"; * 一次类推 */ public static String CharAtreverse(String s) { int length = s.length(); String reverse = ""; for (int i=0; i<length; i++) reverse = s.charAt(i) + reverse; return reverse; }
3. 通过String的toCharArray()方法可以获得字符串中的每一个字符串并转换为字符数组,然后用一个空的字符串从后向前一个个的拼接成新的字符串
String str = "123456789qwertyuiop"; String reverse = ""; char[] cs = str.toCharArray(); /*for (int i = cs.length -1; i >=0; i--) { reverse +=cs[i]; }*/
//Array.Reverse(cs); for (int i = 0; i < cs.length; i++) { reverse = cs[i]+reverse; } System.out.println(reverse);
4.使用递归法:
public String reverseByRecursion(String str) { int length = str.length(); if (length <= 1) { return str; } return reverseByRecursion(str.substring(1)) + str.charAt(0); }