Program to reverse the order of words in a sentence



  


Program to reverse the order of words in a sentence

  • Reverse the order of words in a sentence, but keep words themselves unchanged. Words in a sentence are divided by blanks. For instance, the reversed output should be “student. a am I” when the input is “I am a student”..

 public class ReverseWords 
{
public static void main(String[] args) 
{  
    String s="I am a student";
    String result=reverseWord(s);  
    System.out.println(result.substring(1));  
}  
    public static String reverseWord(String s)  
{  
    String[] str=s.split(" ");
    String rev="";
    for(int i=str.length-1;i>=0;i--)
          {  
                rev=rev+" "+str[i];  }  return rev;  
          
}

Post a Comment