java中字符串反转

/*
	 * java中字符串反转
	 * 在Java中的String类是没有reverse方法的
	 * 但是StringBuilder和StringBuffer就有啊,
	 * 所以我们可以写一个算法
	 * */
	public static String ReverseByCharBuffer(String original) {
        char[] c = original.toCharArray();
        int l = c.length;
        //折半换位法
        for (int i = 0; i < l/2; i++) {
            char t = c[i];
            c[i] = c[l - i - 1];
            c[l - i - 1] = t;
        }
        return new String(c);
    }  
StringBuilder sbBuilder=new StringBuilder("asdf");
	 	 sbBuilder.reverse();

public AbstractStringBuilder reverse() {
        boolean hasSurrogates = false;
        int n = count - 1;
        for (int j = (n-1) >> 1; j >= 0; j--) {
            int k = n - j;
            char cj = value[j];
            char ck = value[k];
            value[j] = ck;
            value[k] = cj;
            if (Character.isSurrogate(cj) ||
                Character.isSurrogate(ck)) {
                hasSurrogates = true;
            }
        }
        if (hasSurrogates) {
            reverseAllValidSurrogatePairs();
        }
        return this;
    }

    /** Outlined helper method for reverse() */
    private void reverseAllValidSurrogatePairs() {
        for (int i = 0; i < count - 1; i++) {
            char c2 = value[i];
            if (Character.isLowSurrogate(c2)) {
                char c1 = value[i + 1];
                if (Character.isHighSurrogate(c1)) {
                    value[i++] = c1;
                    value[i] = c2;
                }
            }
        }
    }


你可能感兴趣的:(java,J2SE)