In this post, you will learn how to reverse the words in a given string sentence using Java. To reverse the words in a given String sentence in Java, you can split the sentence into words, reverse their order, and then join them back into a new sentence.
Here’s how you can achieve this:
package com.javacodepoint.string;
public class ReverseWordsInSentence {
public static String reverseSentence(String input) {
if (input == null || input.isEmpty()) {
return input; // If the input is null or empty, return as it is.
}
// Split the input sentence into words
String[] words = input.trim().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(" "); // Add space between words
}
}
return reversedSentence.toString();
}
public static void main(String[] args) {
String sentence = "This is a sample string sentence";
String reversedSentence = reverseSentence(sentence);
System.out.println("Input Sentence: " + sentence);
System.out.println("Reversed Sentence: " + reversedSentence);
}
}
OUTPUT:
Input Sentence: This is a sample string sentence.
Reversed Sentence: sentence. string sample a is This
Explanation:
In this program, we first split the input sentence into words using the split
method with the regular expression "\\s+"
, which matches one or more whitespace characters (spaces, tabs, or newlines). The resulting words
array contains individual words.
Next, we create a StringBuilder
named reversedSentence
to build the reversed sentence. We iterate through the words
array in reverse order, appending each word to the reversedSentence
. We also add a space between words (except before the first word) to separate them properly.
Finally, we return the reversedSentence
as the reversed sentence.
Learn also: Reverse a string without using the reverse() method.