Reverse Words in a Sentence in Java
Reversing words in a sentence means reversing the characters of each word individually while keeping the original order of words unchanged.
This type of string manipulation is frequently asked in interviews and is useful for understanding character-level string processing.
Understanding the Problem
We do not reverse the entire sentence. Instead, each word is reversed at its own place.
Example 1
Input: Java is fun
Output: avaJ si nuf
Example 2
Input: Hello World
Output: olleH dlroW
Logic Explanation
- Traverse the string character by character.
- Store characters of a word temporarily.
- When a space is encountered, reverse the stored word.
- Append the reversed word to the result.
- Repeat until the end of the string.
Java Program to Reverse Words in a Sentence
import java.util.Scanner;
public class ReverseWordsInSentence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String str = sc.nextLine();
String word = "";
String result = "";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != ' ') {
word = ch + word; // reverse the word
} else {
result = result + word + " ";
word = "";
}
}
// add last word
result = result + word;
System.out.println("Reversed words sentence: " + result);
}
}
Sample Output
Enter a sentence: Java is fun
Reversed words sentence: avaJ si nuf
Key Points
- Word order remains unchanged.
- Each word is reversed individually.
- No use of
split()orStringBuilder.reverse().
Practice Challenges
- Reverse the order of words instead of characters.
- Handle multiple spaces between words.
- Rewrite the program using
StringBuilder.
This program helps strengthen understanding of strings, loops, and conditional logic in Java.