這裡介紹Java中5中實現String反轉的方式。
//數組實現String反轉 public String reverseByArray(){ if(str == null || str.length() == 1){ return null; } char[] ch = str.toCharArray();//字符串轉換成字符數組 for(int i = 0 ; i < ch.length/2 ; i++){ char temp = ch[i]; ch[i] = ch[ch.length-i-1]; ch[ch.length-i-1] = temp; } return new String(ch); }
//用棧實現String反轉 public String reverseByStack(){ if(str == null || str.length() == 1){ return null; } Stack<Character> stack = new Stack<Character>(); char[] ch = str.toCharArray();//字符串轉換成字符數組 for (char c : ch) { stack.push(c);//每個字符,推進棧 } for (int i = 0; i < ch.length; i++) { ch[i] = stack.pop();//移除這個堆棧的頂部對象 } return new String(ch); }
//用逆序遍歷實現String反轉 public String reverseBySort(){ if(str == null || str.length() == 1){ return null; } StringBuffer sb = new StringBuffer(); for (int i = str.length() -1 ; i >= 0; i--) { sb.append(str.charAt(i));//使用StringBuffer從右往左拼接字符 } return sb.toString(); }
//使用位運算實現String反轉 public String reverseByBit() { if(str == null || str.length() == 1){ return null; } char[] ch = str.toCharArray();//字符串轉換成字符數組 int len = str.length(); for(int i= 0; i< len/ 2; i++) { ch[i]^= ch[len- 1- i]; ch[len- 1- i]^= ch[i]; ch[i]^= ch[len- 1- i]; } return new String(ch); }
//使用遞歸實現String反轉 public String reverseByRecursive(String str){ if(str == null || str.length() == 0){ return null; } if(str.length() == 1){ return str; } else { //從下標為1開始截取字符串,在返回下標為0的字符 return reverseByRecursive(str.substring(1)) + str.charAt(0); } }
public class Test { public static void main(String[] args) { String s = "123456"; Reverse r = new Reverse(s); System.out.println(r.reverseByArray()); System.out.println(r.reverseByStack()); System.out.println(r.reverseBySort()); System.out.println(r.reverseByBit()); System.out.println(r.reverseByRecursive(s)); } }