Please let me know a better approach to solve below problem:
Problem: Vertically arrange the words in a string and print on console.
Sample Input:
Hello Jack
Output:
H J e a L c L k o
My solution:
public static void toVerticalWords(String str){
//split the words by whitespace
String[] strArr = str.split("\\s");
int maxWordLen = 0;
//get the longest word length
for(String strTemp : strArr) {
if(strTemp.length() > maxWordLen)
maxWordLen = strTemp.length();
}
//make a matrix of the words with each characetrcharacter in an array block
char[][] charArr = new char[strArr.length][maxWordLen];
for(int i=0; i<strArr.length; i++) {
int j=0;
for(char ch : strArr[i].toCharArray()){
charArr[i][j] = ch;
j++;
}
}
//print the vertical word pattern, or transpose of above matrix (2D array)
for(int j=0; j<maxWordLen; j++) {
for(int i=0; i<strArr.length; i++) {
if (i!=0)
System.out.print(" ");
System.out.print(charArr[i][j]);
}
System.out.println();
}
}