Question: Write a Java method named reverseWords
that takes in a string parameter sentence
and returns a new string with each word in sentence
reversed. The words in the returned string should be in the same order as they appear in sentence
, but the characters in each word should be reversed. The method should ignore any punctuation or special characters and treat them as part of the word.
For example, if the method is called as follows:
reverseWords("Hello world! How are you?");
The method should return the following string:
olleH dlrow woh era ?uoy
Implement the reverseWords
method. You may assume that the input string is non-null and contains at least one word.
public class StringManipulation {
public static String reverseWords(String sentence) {
String[] words = sentence.split("\\s+");
StringBuilder reversedSentence = new StringBuilder();
for (String word : words) {
StringBuilder reversedWord = new StringBuilder(word);
// Reversing the characters in the word
reversedWord.reverse();
// Appending the reversed word to the reversed sentence
reversedSentence.append(reversedWord).append(" ");
}
// Removing trailing whitespace from the reversed sentence
return reversedSentence.toString().trim();
}
public static void main(String[] args) {
String sentence = "Hello world! How are you?";
String reversedSentence = reverseWords(sentence);
System.out.println(reversedSentence);
}
}
Explanation:
The reverseWords
method first splits the input sentence
into an array of words using the split("\\s+")
method. The regular expression \\s+
matches one or more consecutive whitespace characters, ensuring that multiple spaces between words are treated as a single separator.
Then, for each word in the words
array, a new StringBuilder
named reversedWord
is created to store the reversed characters of the word. The reverse()
method is called on reversedWord
to reverse its contents.
Next, the reversed word is appended to the reversedSentence
StringBuilder with a space character (' ') appended after each word.
Finally, any trailing whitespace from the reversedSentence
StringBuilder is removed using the trim()
method, and the resulting reversed sentence string is returned.
In the provided main
method, the reverseWords
method is called with the sentence "Hello world! How are you?"
, and the reversed sentence is printed to the console.
Output:
olleH dlrow woh era ?uoy