I need to make a 2D array from a given String. A number of rows will be a number of words in String and the number of columns will be the length of the longest word in String (words are separated with space). If in the String there is a 2 letter word (for example "is") and the column number will be 8 I need to fill the rest of the cells with space.
Example:
String: "aaa bbbb ccccc dddddd"
Array: stringArray[4][6]
Output: {{a,a,a,' ',' ',' '},{b,b,b,b,' ',' '},{c,c,c,c,c,' '},{d,d,d,d,d,d}}
The code is:
public static void TextToArray(String s) {
int rowCount = 0;
int columnCount = 0;
int tempColumn = 0;
//getting array dimensions and creating an array
for (int i = 0; i < s.length(); i++) {
tempColumn++;
if (s.charAt(i) == ' ') {
rowCount++;
if (tempColumn > columnCount) {
columnCount = tempColumn;
}
tempColumn = 0;
}
}
char[][] stringArray = new char[rowCount + 1][tempColumn];
//filling array - not completed
for (int i = 0; i < stringArray.length ; i++) {
for (int j = 0; j < stringArray[i].length ; j++) {
if(s.charAt(j) == ' '){
for (int k = j; k < stringArray[i].length - j ; k++) {
stringArray[i][j] = ' ';
}
}
stringArray[i][j] = s.charAt(j);
System.out.print(stringArray[i][j] + ", ");
}
System.out.println();
}
I have a problem with inserting spaces to empty cells (i have no idea - i need some pointers to make it). Im also stuck on place where j loop is ending and starting from the beggining (the letters that loop is inserting to array starts from the beginning of the string - i have no clue where to instert condition to continiue iterating through String length). I know that the second part of method is bad but i need help to end it.