Java Challenge: Word Reversal
“Suppose someone imagined a blue and white striped unicorn.”
I began to work on some simple Java Challenges to polish my core java skills after spending so many months with the Spring Framework. This is the first one I wish to share:
Word Reversal Challenge
For this challenge, the input is a string of words, and the output should be the words in reverse but with the letters in the original order.
I began to explore how to just reverse a string. Which was very straight forward using StringBuilder class.
String input = "Suppose someone imagined a blue and white striped unicorn.";
String reverseString = new StringBuilder(userInput).reverse().toString();
// Output: .nrocinu depirts etihw dna eulb a denigami enoemos esoppuS
Then, I wanted to keep the sentence order. However, this initial exercise still reversed the characters.
First, we split the sentence into an array of words. Then we create a for loop to reverse each word, surrounded by another for loop to rearrange each word. Not sure why I was rearranging the characters, but I figured I could then just reverse the words, NOT the characters. Hey, that is why they are called challenges. They are not hard, but they train you to think. Even simple things like these.
public static String reversedButKeepSentenceOrder(String userInput) {
String sentence[] = userInput.split(" ");
String reverse = "";
for (String word : sentence) {
String reverseWord = "";
for (int i = sentence.length - 1; i >= 0; i--) {
reverseWord = reverseWord + word.charAt(i);
}
reverse = reverse + reverseWord + " ";
}
return reverse;
}
// Output: esoppuS enoemos denigami a eulb dna etihw depirts .nrocinu
Now, the actual challenge was to reverse it full but legible. Inspired by the previous one. We just create an array of the words in the sentence and reverse it! It is actually much more efficient than the initial way. The for loop evaluates the sentence length, so each word, and then reverse them with a space after each word. There is no need to reverse characters! Why did it take me so long?…
public static String shortWay(String userInput) {
String sentence[] = userInput.split(" ");
String reverse = "";
for (int i = sentence.length - 1; i >= 0; i--) {
reverse += sentence[i] + " ";
}
return reverse;
}
// Output: unicorn. striped white and blue a imagined someone Suppose
Extra challenge
Make the string reverse with correct capitalization.
Easy! Same code as above and then:
return reverse.substring(0, 1).toUpperCase() + reverse.substring(1).toLowerCase();
// Output: Unicorn. striped white and blue a imagined someone suppose
The first substring will change the first letter to cap. In the second, instruct the string to turn fully to lower case, else we get the S still capitalized.
That was fun! I’ll post the rest as I solve them 🙂