Reverse Words in String
This program reverses words in a string.
Problem Statement
Write a Java program to reverse words in a given string.
Source Code
| 1 | public class ReverseWords { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq Reverse Words"); |
| 4 | String str="Hello Eduinq World"; |
| 5 | String[] words=str.split(" "); |
| 6 | String result=""; |
| 7 | for(int i=words.length-1;i>=0;i--){ |
| 8 | result+=words[i]+" "; |
| 9 | } |
| 10 | System.out.println("Reversed words: "+result.trim()); |
| 11 | } |
| 12 | } |
Program Output
Eduinq Reverse Words Reversed words: World Eduinq Hello
Explanation
The string is split into individual words using split(" "), and a loop iterates backwards through the words array to build the result in reverse order, demonstrating word-level reversal.