1. 程式人生 > >字元陣列或字串逆轉的幾種方法

字元陣列或字串逆轉的幾種方法

public class Test {
	
	public static void main(String[] args) {
	
		//字元逆轉
		char[] ss=new char[]{'a','b','c'};
//		char[] temp = new char[ss.length];
//		int count = 0;
//		
//		for(int i = ss.length - 1; i >= 0 && count < temp.length; i--){
//			temp[count] = ss[i];
//			count++;
//		}
//		ss = temp;
//		
//		System.out.println(ss);
		
		//字元逆轉
		String s = new String(ss);
		StringBuffer sb = new StringBuffer(s);
		sb.reverse();
		ss = sb.toString().toCharArray();
		System.out.println(ss);

		//字串逆轉
		String str = "abc123";
		StringBuffer sb1 = new StringBuffer(str);
		System.out.println(sb1.reverse());
		
		// 字串逆轉
		String str1 = "abc123";
		StringBuilder sb2 = new StringBuilder();
		
		for(int i = str1.length() - 1; i >= 0; i-- ){
			char c = str1.charAt(i);
			sb2.append(c);
		}
		str1 = sb2.toString();
		System.out.println(str1);
	}
	
}