我的教授在本周的期中考试中给出了一个复习题,我对此感到困惑:
编写一个方法,该方法给出一个二维(参差不齐的)数组 String 对象并返回 String 的二维(参差不齐)数组 所有空条目已被删除的对象。例如, 如果原始数组有数据(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], []]
。
编辑:更新了一些评论。
关于java - 从不规则的二维字符串数组中删除字符串并在此过程中缩短数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34293326/