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
String split into words using split(" "). - Loop iterates backwards to reverse order. - Together demonstrates word reversal. Conclusion: Shows how to reverse words in a string.