Question:
Write a Java method, reverseWords
, that takes a String as input and returns a new String with the words reversed (but keeping the words in the original order).
The method should assume that words in the input String are separated by a single space and that there are no leading or trailing spaces. Additionally, the input String will not be empty.
For example, given the input String "hello world java", the method should return "olleh dlrow avaj".
Write the reverseWords
method and provide a step-by-step explanation of your implementation.
Answer:
public class StringManipulation {
public static String reverseWords(String input) {
// Split the input String into an array of words
String[] words = input.split(" ");
// Create a StringBuilder object to store the reversed words
StringBuilder reversedWords = new StringBuilder();
// Iterate over each word in the words array
for (int i = 0; i < words.length; i++) {
// Reverse the current word and append it to the reversedWords StringBuilder
String reversedWord = reverseWord(words[i]);
reversedWords.append(reversedWord);
// Append a space after every word except the last word
if (i < words.length - 1) {
reversedWords.append(" ");
}
}
// Convert the StringBuilder object to a String and return the result
return reversedWords.toString();
}
// Helper method to reverse a word
private static String reverseWord(String word) {
StringBuilder reversedWord = new StringBuilder(word);
return reversedWord.reverse().toString();
}
}
Step-by-step explanation:
reverseWords
method takes a String input as a parameter.split
method and stores it in the words
array.StringBuilder
object called reversedWords
is created to store the reversed words.for
loop iterates over each word in the words
array.reverseWord
helper method is called to reverse the current word stored in words[i]
.reversedWords
StringBuilder object.reversedWords
StringBuilder.reversedWords
StringBuilder is converted to a String using the toString
method and returned as the result.