Java笔试之几种字符串逆序的方法

package test;

import java.util.Stack;

public class DoString {

	public static void main(String[] args) {
		String string = "123abcd";
		// StringBuffer sb = new StringBuffer(string);
		string = reverse3(string);
		// System.out.println(sb.reverse().toString());
		System.out.println(string);

	}

	public static String reverse3(String string) {
		StringBuffer sb = new StringBuffer();
		Stack s = new Stack();
		for (int i = 0; i < string.length(); i++) {
			s.add(string.charAt(i));
		}
		for (int i = 0; i < string.length(); i++) {
			sb.append(s.pop());
		}
		return sb.toString();
	}

	public static String reverse1(String string) {
		StringBuffer sb = new StringBuffer(string);
		for (int i = 0, j = sb.length() - 1; i < sb.length() >>> 1; i++, j--) {
			char temp = sb.charAt(i);
			sb.setCharAt(i, sb.charAt(j));
			sb.setCharAt(j, temp);
		}
		return sb.toString();
	}

	public static String reverse2(String string) {
		StringBuffer sb = new StringBuffer();
		for (int i = string.length() - 1; i >= 0; i--) {
			sb.append(string.charAt(i));
		}
		return sb.toString();
	}

}

你可能感兴趣的:(Java)