Java 将语句里的空格替换为#

 public static int getCountBlank(char[] arr) {
        int count = 0;
        for (int i = 0; i < arr.length; i++) {//14
            if (arr[i] == ' ') {
                count++;
            }
        }
        return count;
    }

    public static char[] replace(char[] arr) {
        int countBlank = getCountBlank(arr);//3
        int srcLength = arr.length;//14
        //1扩容:
        arr = Arrays.copyOf(arr, arr.length + countBlank);
        //arr.length->新数组长度
        //2 遍历  涉及数据的移动
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == ' ') {
                arr[i] = '#';
                //移动
                for (int j = srcLength - 1; j > i; j--) {
                    arr[j + 1] = arr[j];
                }
                arr[i + 1] = '#';
                srcLength += 1;
            }
        }
        return arr;
    }

    public static void main(String[] args) {
        String str = "i am a studnet.";
        char[] arr = str.toCharArray();//14
        System.out.println(arr.length);
        arr = replace(arr);
        System.out.println(Arrays.toString(arr));
    }
}

你可能感兴趣的:(Java 将语句里的空格替换为#)