I've been trying to learn Java and one way I've been teaching myself is by tackling "programming challenge questions".
One such question is "reverse the character order of words in a string".
For example, " I have a hat "
=> " I evah a tah "
(note the spaces). In my implementation, I don't deal with punctuation, so "I have a hat!"
=> "I evah a !tah"
.
I've written an implementation and I'd like some feedback, particularly regarding the readability and efficiency of the code (basically, is there a slicker implementation of what I'm trying to accomplish - to me, the answer is yes, especially the last part of my implementation).
The implementation is basically doing the following:
- Create a one element-sized String array called
candidateReversedWordsString
and initialize it with the input String - Create a StringBuilder that will build all the reversed words.
- Iterate through the characters in the string
- If the character is not a space and the StringBuilder is empty, note the character index value in the
wordStartIndex
variable and add the character to the StringBuilder. - If the character is not a space and the StringBuilder is not empty, add the character to the StringBuilder
- If the character is a space and the StringBuilder is not empty, take the only element in the
candidateReversedWordsString
array and basically concatenate the element with the reversed word from the StringBuilder using substrings. - If at the final character and the StringBuilder is not empty, slight adjustment to the concatenation
public String reverseWordsInString(final String string) {
final String[] candidateReversedWordsString = new String[1];
candidateReversedWordsString[0] = string;
int stringCharacterIndex = 0;
int wordStartIndex = 0;
final StringBuilder reverseWordStringBuilder = new StringBuilder();
while (stringCharacterIndex < string.length()) {
if (' ' != string.charAt(stringCharacterIndex)) {
if (reverseWordStringBuilder.length() == 0) {
wordStartIndex = stringCharacterIndex;
}
reverseWordStringBuilder.append(string.charAt(stringCharacterIndex));
}
if (' ' == string.charAt(stringCharacterIndex) && reverseWordStringBuilder.length() > 0) {
candidateReversedWordsString[0] = new StringBuilder().
append(candidateReversedWordsString[0].substring(0, wordStartIndex)).
append(reverseWordStringBuilder.reverse().toString()).
append(candidateReversedWordsString[0].substring(stringCharacterIndex)).toString();
reverseWordStringBuilder.setLength(0);
}
if (stringCharacterIndex == string.length() - 1 && reverseWordStringBuilder.length() > 0) {
candidateReversedWordsString[0] = new StringBuilder().
append(candidateReversedWordsString[0].substring(0, wordStartIndex)).
append(reverseWordStringBuilder.reverse().toString()).toString();
}
stringCharacterIndex++;
}
return candidateReversedWordsString[0];
}