HWrite a Java method reverseWords
that returns the string with the words reversed, but the characters in each word remain in the same order.
Example:
Input:
javaCopy code" Java is fun "
Output:
javaCopy code"fun is Java"
Sample Solution:
javaCopy codepublic class ReverseWords {
public static void main(String[] args) {
String sentence = " Java is fun ";
System.out.println(reverseWords(sentence));
}
public static String reverseWords(String s) {
// Trim leading and trailing spaces
s = s.trim();
// Split the string by one or more spaces
String[] words = s.split("\\s+");
// Reverse the order of words
StringBuilder reversedSentence = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversedSentence.append(words[i]);
if (i != 0) {
reversedSentence.append(" ");
}
}
return reversedSentence.toString();
}
}
Explanation:
- Trimming Spaces:
We uses.trim()
to remove leading and trailing spaces from the input string. - Splitting by Spaces:
We split the input string by one or more spaces using the regex\\s+
to handle multiple spaces between words. - Reversing the Words:
We iterate over the array of words in reverse order and append them to aStringBuilder
to create the reversed sentence. - Return the Result:
The final reversed string is returned and printed out.
Leave a Comment