从参差不齐的二维字符串数组中删除字符串并在此过程中缩短数组

Removing a String from a ragged 2D String array and shortening the array in the process

我的教授给出了本周期中考试的复习题,我对此感到困惑:

编写一个方法,给定一个二维(参差不齐的)数组 String 对象和 returns String 的二维(参差不齐)数组 已删除所有空条目的对象。例如, 如果原始数组有数据(NULL 代表一个 null 参考):

{"John", null, "Mary", "George", null},{null, "Pete", "Rick"},{null, null, null}};

您的方法生成的结果将是二维的 三行数组。

{"John", "Mary", "George"},{"Pete", "Rick"},{}}; // last row will be empty

我的密码是:

public static String[][] removeNull2D(String[][] ragged) {
    int counter = 0;
    int nullCounter = 0;
    String[][] array; // isn't initialized

    // doesn't work I tested in debugger, need a way to shorten each row by the amount of null values it has
    for (int i = 0; i < ragged.length; i++) {
        for (int j = 0; j < ragged[i].length; j++) {
            if (ragged[i][j] == null) {
                nullCounter++;
                for (j = 0; j < ragged[i].length; j++) {
                    array = new String[ragged.length][ragged[i].length - nullCounter];
                }
            }
        }
    }
    // based off 1D array approach
    for (int i = 0; i < ragged.length; i++) {
        for (int j = 0; j < ragged[i].length; j++) {        
            if (ragged[i][j] != null) {
                array[i][counter++] = ragged[i][j];
            }
        }
    }
    return ragged;
}

我知道我需要计算每行中空值的数量,并从字符串数组 "array"(我知道的坏名字)的每行总长度中减去它。我想也许如果我为一维数组创建一个方法,它会帮助我更好地理解逻辑:

public static String[] removeNull1D(String[] a) {
    String[] array = new String[a.length - 1];
    int counter = 0;

    for (int i = 0; i < a.length; i++) {
        if (a[i] != null) {
            array[counter++] = a[i];
        }
    }
    a = array;
    return array;
}

仍然对逻辑如何应用于二维参差不齐的数组方法感到困惑,如有任何澄清,我们将不胜感激!另外,我不相信我可以导入任何东西(至少不应该),再一次,这只是一个复习问题,所以我并不强调要得到答案,只是想了解它背后的逻辑。

你可以这样试试:

public static void main(String[] args) {
    String[][] ragged = { { "John", null, "Mary", "George", null }, { null, "Pete", "Rick" }, { null, null, null } };

    String[][] cleaned = new String[ragged.length][];
    for (int i = 0; i < ragged.length; i++) {
        cleaned[i] = clean(ragged[i]); // Apply clean method to each sub array.
    }

    System.out.println(Arrays.deepToString(cleaned));
}

private static String[] clean(String[] dirty) {
    int nonNullCount = 0;
    for (String string : dirty) {
        if (string != null) {
            nonNullCount++; // Count non-null Strings.
        }
    }
    String[] clean = new String[nonNullCount]; // Create array for non-null Strings.
    int cleanIndex = 0;
    for (String string : dirty) {
        if (string != null) {
            clean[cleanIndex] = string; // Insert only non-null String at index.
            cleanIndex++; // Only then update index.
        }
    }
    return clean;
}

对我来说似乎有点不雅,但目前我想不出一种方法来防止 clean(String[] dirty)

中的双循环

尽管如此,它会根据需要输出 [[John, Mary, George], [Pete, Rick], []]

编辑:更新了一些评论。