Java Program to Reverse Words in a Sentence

Java Program to Reverse Words in a Sentence : In Java we can reverse each word in a sentence using String Methods. In this program, we are usingĀ JOptionPane.showInputDialog() method of javax.swing package to accept input from user. In java inputs are String by default.

//Java Programe to Reverse Words in a Sentence

import javax.swing.*;
class StrRev
{
public static void main(String arg[])
{
String name=JOptionPane.showInputDialog("Enter a sentence");
name+=" ";
int i,k;
String revstr="",str="";
for(i=0;i<name.length();i++)
{
        str+=name.charAt(i);
        if(name.charAt(i)==' ')
        {
               for(k=str.length()-1;k>=0;k--)
	       {
		       revstr+=str.charAt(k);
	       }
	str="";
	}
}
System.out.println("Revserse of Sentence is : "+revstr);
}
}

Input  : THIS IS EXAMPLE
Output : SIHT SI ELPMAXE

 

Share with your Friends...
Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *

The NuCaptcha API requires the PHP mcrypt module.