java字符串反转的7种方法
程序员文章站
2022-06-11 14:35:40
目录1、用stringbuffer或者stringbuilder自带的reverse方法2、将字符串拆分为char数组3、stringbuffer倒序拼接4、利用栈的先进后出5、二分换位反转6、切割递...
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字符串反转内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: 婴幼儿补钙的饮食误区与注意事项
下一篇: 3Dsmax9怎么给弹簧添加动画效果?