将2d数组中每行的空元素移到该行的末尾 [英] Move null elements for each row in 2d array to the end of that row
本文介绍了将2d数组中每行的空元素移到该行的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个二维数组,如下所示:
Let's say I have a 2d array which looks like this:
[[O, X, null, O, O, null, null], [null, null, O, null, null, O, O]]
我希望它看起来像这样:
And I want it to look like this:
[[O, X, O, O, null, null, null], [O, O, O, null, null, null, null]]
我尝试过此方法,但是它不起作用:
I tried this, but it's not working:
String[][] a = new String[row][col];
String[][] b = new String[row][col];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
if (a[i][j] != null) {
a[i][j] = b[i][j];
} else {
b[i][j] = a[i][j + 1];
}
}
}
推荐答案
一些问题可以解决
- 您需要将
a [i] .length
用于内部循环 -
a [i] [j] = b [i] [j];
在这里,您需要在b
- 您需要为
b
2D数组的每一行使用一个计数器索引,只要发现存储后的非空增量就为null,其余索引按defult为空.
- You need to use
a[i].length
for inner loop a[i][j] = b[i][j];
here you need to assigna
value inb
- You need to use a counter index for
b
2D array's every row and whenever found not-null increment this after storing and remaining index are by defult null.
for (int i = 0; i < a.length; i++) {
int indNew = 0; // Index for every row
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] != null) {
b[i][indNew] = a[i][j]; // store not null value
indNew++; // increase after storing
}
}
}
这篇关于将2d数组中每行的空元素移到该行的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文