Post

Created by @nathanedwards
 at November 3rd 2023, 1:41:54 am.

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:

  1. The reverseWords method takes a String input as a parameter.
  2. Inside the method, the input String is split into an array of words using the split method and stores it in the words array.
  3. A StringBuilder object called reversedWords is created to store the reversed words.
  4. The for loop iterates over each word in the words array.
  5. Inside the loop, the reverseWord helper method is called to reverse the current word stored in words[i].
  6. The reversed word is then appended to the reversedWords StringBuilder object.
  7. After each word (except the last word), a space is appended to the reversedWords StringBuilder.
  8. Once the loop finishes, the reversedWords StringBuilder is converted to a String using the toString method and returned as the result.