#Variable Names
Variable Names
Your variables names are unnecessarily abbreviated and genetic. Also suffixes such as Arr
are usually unnecessary. Here some examples I'd use:
str
=>sentence
strArr
=>words
strTemp
=>word
#Algorithm
Algorithm
You could drop copying the strings into the character array, by using strArr
directly and simply checking if j
exceeds the length of the word and printing a space if it does.
Also getting the maximal word length could also be avoided, if you check during output, if all strings are shorter than j
.
#My version
My version
public static void toVerticalWords(String sentence){
String[] words = sentence.split("\\s");
boolean allWordsEnded;
int row = 0;
do {
allWordsEnded = true;
char[] output = new char[words.length * 2];
int column = 0;
for (String word : words) {
char c;
if (row < word.length()) {
c = word.charAt(row);
allWordsEnded = false;
} else {
c = ' ';
}
output[column++] = c;
output[column++] = ' ';
}
if (!allWordsEnded) {
System.out.println(output);
}
row++;
}
while (!allWordsEnded);
}
The main loop is a bit more complicated, because I cache the line to be written, so when all words have ended, it won't output a line of spaces.