本文實例為大家分享了java字符串反轉(zhuǎn)的具體代碼,供大家參考,具體內(nèi)容如下
創(chuàng)新互聯(lián)建站專注于企業(yè)成都全網(wǎng)營銷推廣、網(wǎng)站重做改版、磐石網(wǎng)站定制設(shè)計、自適應(yīng)品牌網(wǎng)站建設(shè)、H5建站、商城開發(fā)、集團公司官網(wǎng)建設(shè)、成都外貿(mào)網(wǎng)站制作、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁設(shè)計等建站業(yè)務(wù),價格優(yōu)惠性價比高,為磐石等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。import java.util.Stack; public class StringReverse { // 使用內(nèi)置類(StringBuilder或StringBuffer) public static String reverse1(String s) { // StringBuilder strBuilder = new StringBuilder(s); // String ret = strBuilder.reverse().toString(); StringBuffer strBuf = new StringBuffer(s); String ret = strBuf.reverse().toString(); return ret; } // 有左到右 拼接字符串 public static String reverse2(String s) { String ret = ""; for (int i = 0; i < s.length(); ++i) { ret = s.charAt(i) + ret; } return ret; } // 從右到左 拼接字符串 public static String reverse3(String s) { String ret = ""; for (int i = s.length() - 1; i >= 0; --i) { ret += s.charAt(i); } return ret; } public static String reverse4(String s) { String ret = ""; char[] charArr = s.toCharArray(); int len = charArr.length; for (int i = 0; i < len / 2; ++i) { char tmp = charArr[i]; charArr[i] = charArr[len - 1 - i]; charArr[len - 1 - i] = tmp; } ret = new String(charArr); return ret; } // 使用異或 public static String reverse5(String s) { String ret = ""; char[] charArr = s.toCharArray(); int begin = 0, end = charArr.length - 1; while (begin < end) { charArr[begin] = (char) (charArr[begin] ^ charArr[end]); charArr[end] = (char) (charArr[begin] ^ charArr[end]); charArr[begin] = (char) (charArr[begin] ^ charArr[end]); begin++; end--; } ret = new String(charArr); return ret; } // 使用棧 public static String reverse6(String s) { String ret = ""; Stackstack = new Stack (); for (int i = 0; i < s.length(); ++i) { stack.push(s.charAt(i)); } while (!stack.isEmpty()) { ret += stack.pop(); } return ret; } }