java字符串反转的7种方法

目录

  • 1、用stringBuffer或者stringBuilder自带的reverse方法
  • 2、将字符串拆分为char数组
  • 3、stringBuffer倒序拼接
  • 4、利用栈的先进后出
  • 5、二分换位反转
  • 6、切割递归反转
  • 7、二分递归反转

1、用stringBuffer或者stringBuilder自带的reverse方法
public static String reverseTestOne(String s) {return new StringBuffer(s).reverse().toString(); }


2、将字符串拆分为char数组
public static String reverseTestTwo(String s) {char[] charArray = s.toCharArray(); int start = 0, end = charArray.length - 1; for (; start < end; start++, end--) {charArray[start] ^= charArray[end]; //采用异或charArray[end] ^= charArray[start]; charArray[start] ^= charArray[end]; }return new String(charArray); }

两数交换除了用异或还能用其他方法,请移步不借助第三变量实现两数交换

3、stringBuffer倒序拼接
public static String reverseTestThree(String s) {StringBuffer sb = new StringBuffer(); for (int i = s.length() - 1; i >= 0; i--) {sb.append(s.charAt(i)); }return sb.toString(); }


4、利用栈的先进后出
public static String reverseTestFour(String s) {StringBuffer sb = new StringBuffer(); Stack stack = new Stack(); for (int i = 0; i < s.length(); i++) {stack.push(s.charAt(i)); }while (!stack.isEmpty()) {//stack会返回栈顶值,并且会把该值删除sb.append(stack.pop()); }return sb.toString(); }


5、二分换位反转
public static String reverseTestFive(String s) {int start = 0; int end = s.length() - 1; char[] charArray = s.toCharArray(); while (start < end) {//交换首尾char值char c = charArray[end]; charArray[end] = charArray[start]; charArray[start] = c; start++; end--; }return new String(charArray); }


6、切割递归反转
public static String reverseTestSix(String s) {if (s.length() <= 1) {return s; }return reverseTestSix(s.substring(1)) + s.substring(0, 1); }


7、二分递归反转
public static String reverseTestSeven(String s) {int length = s.length(); if (length <= 1) return s; String left = s.substring(0, length / 2); String right = s.substring(length / 2, length); return reverseTestSeven(right) + reverseTestSeven(left); }

【java字符串反转的7种方法】到此这篇关于java字符串反转的7种方法的文章就介绍到这了,更多相关java字符串反转内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读