[英]How do I remove empty spaces from a (5x5) 2d array in java, thus shifting values in the array?
我有一個5x5的數組,我試圖1)根據用戶的String(完成的)輸入的字符刪除字符,2)將數組的值向右移動,從而為用戶輸入的String(不是完成)。
現在,如果我輸入“ Jake”,則用戶輸入為:
bcd
fgh
lmnop
qrstu
vwxyz
(這是因為'j''a''k'和'e'已被刪除..請忽略'i'的缺失,因為賦值使用'i'和'j'作為相同字符以便擠壓到5x5陣列)
我希望“ b”位於第一行的末尾(並位於grid [0] [4]),以便我可以將“ Jake”放到開頭。 請讓我知道如何修改我的代碼以完成此工作,如果可以的話,可以從右下方“修剪”圖形。 任何幫助表示贊賞!
`
grid = new char[5][5];
char ch = 'a';
for (row = 0; row < 5;row++)
{
for (col = 0; col < 5; col++)
{
if(ch=='i') // if we are at i
{
grid[row][col] = ch; // add i to grid
ch+=2; // increment ch twice (k)
}
else // if we are not dealing with i/j
{
grid[row][col] = ch; // add the char
ch++;
}
}
}
for(row = 0; row < 5; row++)
{
for(col = 0; col < 5; col++)
{
if(key.indexOf(grid[row][col]) >= 0 || (key.indexOf('j') >= 0 && grid[row][col] == 'i'))
{
if(grid[row][col] == 'i' && key.indexOf('j') >= 0)
{
grid[row][col] = '\0';
}
else
{
grid[row][col] = '\0';
}
}
}
`
為此,您可以從最后一個元素(即@ [5] [5])遍歷矩陣。如果找到空字符,請向前推找到的第一個非空字符以填補空白。 例如,從z開始
bcd
fgh
lmnop
qrstu
vwxyz
您將在[2] [5]處找到第一個非空對象,因此將h推至[2] [5]。 您再次在[2] [4]處為空,因此將g推至[2] [4]。 繼續這樣做,直到達到[1] [1]。 (假設索引從[1] [1]開始)希望有幫助。
如果將矩陣表示為String
,則容易得多。 然后,您可以使用.replaceAll
刪除鍵中的字符:
public static void main(String[] args) {
String key = "Jake";
// Build string
String str = "";
char ch = 'a';
for (int c = 0; c < 25; c++) {
str += ch;
ch++;
if (ch == 'i') {
ch++;
}
}
System.out.println(str);
// Remove chars from key
String modifiedKey = key.toLowerCase().replace('i', 'j');
for (int i = 0; i < key.length(); i++) {
str = str.replaceAll("" + modifiedKey.charAt(i), "");
}
System.out.println(str);
// Add key in the beginning
str = key.toLowerCase() + str;
System.out.println(str);
// Print out
for (int row = 0; row < 5; row++) {
for (int col = 0; col < 5; col++) {
System.out.print(str.charAt(row * 5 + col));
}
System.out.println();
}
}
首先,我建議采用網格線[row] [col] = ch; 在if / else塊之外,出現兩次:
grid = new char[5][5];
char ch = 'a';
for (row = 0; row < 5;row++)
{
for (col = 0; col < 5; col++)
{
grid[row][col] = ch; // add i to grid
if(ch=='i') // if we are at i
{
ch+=2; // increment ch twice (k)
}
else // if we are not dealing with i/j
{
ch++;
}
}
}
接下來,有一種方法可以右移表格中的字符:
private char[][] rightShift(char[][] table) {
int rows = table.length;
int columns = table[0].length;
char[][] result = new char[rows][columns];
int outputIndex = rows*columns - 1;
for (int inputIndex = rows*columns - 1; inputIndex <= 0; inputIndex--) {
int inputRow = inputIndex / rows;
int inputColumn = inputIndex % columns;
int outputRow = outputIndex / rows;
int outputColumn = outputIndex % columns;
if (table[inputRow][inputColumn] != ' ') {
result[outputRow][outputColumn] = table[inputRow][inputColumn];
outputIndex--;
}
}
for (int i = 0 ; i < outputIndex - inputIndex; i++) {
int outputRow = i / rows;
int outputColumn = i % columns;
result[outputRow][outputColumn] = ' ';
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.