Java中手动实现trim方法

如何手写一个trim方法?

思路

  1. 用char数组来接收字符串
  2. 找出左边第一个不为空格的字符的下标
  3. 找出右边第一个不为空格的字符的下标
  4. 使用substring方法,从左下标读取到右下标

我们来看一下代码如何实现

public class StringHomeWork01 {
          
   
    public static void main(String[] args) {
          
   
        String abc = "   a b c ddsa    ";
        char[] chars = abc.toCharArray();           //将字符串中的字符一个个切出来存在char数组中
        String[] array = new String[chars.length];  //这个string数组用于储存char数组中有值的数组的下标
        int count = 0;                             //count用于判断array数组中有多少个不为0的字符
        for (int i = 0; i < chars.length; i++) {
          
   
            if(chars[i] !=  ){
          
   
                for (int j = 0; j < array.length; j++) {
          
   
                    if(array[j] == null) {
          
   
                        array[j] = Integer.toString(i);
                        count++;
                        break;
                    }
                }
            }
        }
        String result = abc.substring(Integer.parseInt(array[0]),Integer.parseInt(array[count-1])+1);
        System.out.println(result);
    }
}

以上是我对手写trim方法的第一想法,我发现在遍历中其实我们只需要获得第一个和最后一个字符的下标,以上流程运行速度慢了一些,可以做的更好以下

public class StringHomeWork01_2 {
          
   
    public static void main(String[] args) {
          
   
        String abc = "   a b c ddsa    ";
        char[] chars = abc.toCharArray();
        int start = 0;
        int end = 0;
        for (int i = 0; i < chars.length; i++) {
          
   
            if(chars[i] !=  ){
          
   
               start = i;
               break;
            }
        }
        for (int i = chars.length-1; i > 0 ; i--) {
          
   
            if(chars[i] !=  ){
          
   
                end = i;
                break;
            }
        }

        String result = abc.substring(start,end+1);
        System.out.println(result);
    }
}
经验分享 程序员 微信小程序 职场和发展