算法:字符串反转

public class StringReverse {

	// StringBuffer
	public static String reverse1(String str) {
		return new StringBuilder(str).reverse().toString();
	}
	
	// toCharArray
	public static String reverse2(String str) {
		char[] chars = str.toCharArray();
		String reverse = "";
		for (int i = chars.length - 1; i >= 0; i--) {
			reverse += chars[i];
		}
		return reverse;
	}
	
	// charAt
	public static String reverse3(String str) {
		String reverse = "";
		int length = str.length();
		for (int i = 0; i < length; i++) {
			reverse = str.charAt(i) + reverse;
		}
		return reverse;
	}

	public static void main(String[] args) {
		String a = "123456";
		
		System.out.println(reverse1(a));
		System.out.println(reverse2(a));
		System.out.println(reverse3(a));
	}

}

猜你喜欢

转载自blog.csdn.net/Mr_BJL/article/details/87870545