java几种字符串反转
java实现的字符串翻转,能想到的这几种方法
假设有其它方法,欢迎交流
//字符串反转 public class ReverseString { public String reverse1(String str){ StringBuffer sb = new StringBuffer(str); str = sb.reverse().toString(); return str; } public String reverse2(String str){ char[] ch = str.toCharArray(); StringBuffer sb = new StringBuffer(); for(int i=ch.length;i>0;i--){ sb.append(ch[i-1]); } return sb.toString(); } public String reverse3(String str){ StringBuffer sb = new StringBuffer(); for(int i=str.length()-1;i>=0;i--){ sb.append(str.charAt(i)); } return sb.toString(); } //O(logn) public String reverse4(String str){ char[] a = str.toCharArray(); for(int i=0;i<str.length()/2;i++){ char temp = a[i]; a[i] = a[a.length-i-1]; a[a.length-i-1] = temp; } return String.valueOf(a); } public String reverse5(String str,int start,int end){ int i=start; int j=end; char[] a = str.toCharArray(); while(i<j){ char temp = a[i]; a[i] = a[j]; a[j] = temp; i++; j--; } return String.valueOf(a); } public static void main(String[] arg){ ReverseString rs = new ReverseString(); String str = "a213aa d43d ddfs"; String s = rs.reverse1(str); System.out.println("reverse1:"+s); s = rs.reverse2(str); System.out.println("reverse2:"+s); s = rs.reverse3(str); System.out.println("reverse3:"+s); s = rs.reverse4(str); System.out.println("reverse4:"+s); s = rs.reverse5(str,0,str.length()-1); System.out.println("reverse5:"+s); } }
转载请注明:http://blog.csdn.net/df1012890048