Sure, here's a computational thinking question related to string manipulation:
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)
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:
We start by creating a class called StringManipulation
with a method reverseWords
that takes a string sentence
as input and returns a string.
Inside the reverseWords
method, we split the input sentence
into individual words using the split
method and store them in an array called words
.
We then create a StringBuilder
called reversedSentence
to store the reversed words.
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.
We then append the reversed word followed by a space to the reversedSentence
StringBuilder.
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".