String类练习:模拟一个trim功能一致的方法

题目:模拟一个trim功能一致的方法

思路:

1、定义两个变量

一个变量作为从头开始判断字符串空格的角标。不断++。

一个变量作为尾头开始判断字符串空格的角标。不断--。

2、判断到不是空格为止,取头尾之间字符串即可。

解题代码:

public class Demo04 {
    public static void main(String[] args) {
        String s = "    qi   u  s  hao ch an  g    ";
        //定义一个自动去空格的方法
        s = myTrim(s);
        //去掉中间的空白地方,不仅仅去掉空格
        s = s.replaceAll("\\s*", "");
        System.out.println("-" + s + "-");
    }
    public static String myTrim(String s) {
        int start = 0, end = s.length() - 1;
        //start指针从头开始不断++,直到碰到不是空格的字符停止
        while (start <= end && s.charAt(start) == ' ') {
            start++;
        }
        //end从尾开始,不断--,直到碰到不是空格的字符停止
        while (start <= end && s.charAt(end) == ' ') {
            end--;
        }
        //截取头和尾,尾部要加1,因为subString(beginIndex,endIndex)包含beginIndex,不包含endIndex
        return s.substring(start, end + 1);
    }
}

猜你喜欢

转载自blog.csdn.net/m0_49517277/article/details/107756249