编程语言
首页 > 编程语言> > Java SE/模拟一 个 trim 方法,去除字符串两端的空格

Java SE/模拟一 个 trim 方法,去除字符串两端的空格

作者:互联网

    /*
        1.将String打散成char数组
        2.遍历char数组,获得第一个非空格字符的下标和最后一个非空格字符的下标
        3.将两个下标间的字符遍历赋予一个新数组
        4.return新数组
     */
    public static String FakeTrim(String str){
        String trStr = str;
        int j = 0;
        char [] cStr = str.toCharArray();
        int firstNum = 0;
        int lastNum  = cStr.length -1;
        for (int i = 0; i < cStr.length ; i++) {
            if(cStr[i] != ' '){
                firstNum = i;
                break;
            }
        }
        for (int i = cStr.length - 1; i >= 0  ; i--) {
            if(cStr[i] != ' '){
                lastNum = i;
                break;
            }
        }
        char [] newStr = new char[lastNum-firstNum + 1];
        for (int i = firstNum; i < lastNum + 1; i++) {
            newStr[j++] = cStr[i];
        }
        String reStr = new String(newStr);
        return reStr;
    }

标签:trim,Java,String,int,char,lastNum,cStr,firstNum,SE
来源: https://blog.csdn.net/weixin_48118167/article/details/121218842