java基础知识回顾之---java String final类普通方法的应用之“模拟字符串Trim方法”

/*
 * 4,模拟一个trim功能一致的方法。去除字符串两端的空白
 * 思路:
 * 1,定义两个变量。
 * 一个变量作为从头开始判断字符串空格的角标。不断++。
 * 一个变量作为从尾开始判断字符串空格的角标。不断--。
 * 2,判断到不是空格为止,取头尾之间的字符串即可。
 *
 *  使用char charAt(int index);方法根据index索引,取出字符串
 *  使用String substring(int beginIndex, int endIndex)//包含begin 不包含end 。截取不含空格的子串
 */

public class StringTrim {

    /**
     * @param args
     */
    public static void main(String[] args) {

        String s = "    ab   c     ";

        s = myTrim(s);
        System.out.println("-" + s + "-");
    }
    /**
     * 
     * @param s 截取的字符串
     * @return 返回截取后的字符串
     */
    public static String myTrim(String s) {

        int start = 0, end = s.length() - 1;

        while (start <= end && s.charAt(start) == ' ') {//start指针从头开始不断++,直到碰到不是空格的字符停止
            start++;
        }
        while (start <= end && s.charAt(end) == ' ') {//end从尾开始,不断--,直到碰到不是空格的字符停止
            end--;
        }
        return s.substring(start, end + 1);//截取头和尾,尾部要加1,因为subString(beginIndex,endIndex)包含beginIndex,不包含endIndex
    }

}
 
原文地址:https://www.cnblogs.com/200911/p/3872930.html