Post

Created by @nathanedwards
 at November 13th 2023, 8:20:29 pm.

Sure, here's a computational thinking question related to string manipulation:

Question:

Write a Java method called reverseWords that takes a string sentence as input and returns the sentence with each word reversed. For example, if the input is "hello world", the method should return "olleh dlrow".

Method Signature:

public String reverseWords(String sentence)

Answer:

public class StringManipulation {
    public static String reverseWords(String sentence) {
        String[] words = sentence.split(" ");
        StringBuilder reversedSentence = new StringBuilder();
        
        for (String word : words) {
            StringBuilder reversedWord = new StringBuilder(word);
            reversedWord.reverse();
            reversedSentence.append(reversedWord).append(" ");
        }
        
        return reversedSentence.toString().trim();
    }

    public static void main(String[] args) {
        String input = "hello world";
        System.out.println(reverseWords(input)); // Output: "olleh dlrow"
    }
}

Explanation:

  1. We start by creating a class called StringManipulation with a method reverseWords that takes a string sentence as input and returns a string.

  2. Inside the reverseWords method, we split the input sentence into individual words using the split method and store them in an array called words.

  3. We then create a StringBuilder called reversedSentence to store the reversed words.

  4. We iterate through each word in the words array using a for-each loop, and for each word, we create a new StringBuilder called reversedWord containing the reversed version of the word using the reverse method.

  5. We then append the reversed word followed by a space to the reversedSentence StringBuilder.

  6. Finally, we return the reversedSentence after converting it to a string using the toString() method and trimming any trailing whitespaces using the trim method.

In the main method, we call the reverseWords method with the input "hello world" and print the output, which should be "olleh dlrow".