← All resources

Write a program to input a string and print each word in reverse.

Example
Enter a string:
This is an example
OutPut:sihT si na elpmaxe

import java.io.*;
public class reverse_each_word
{
    public static void main()throws IOException
    {
        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
        String s, w="", s2="";
        int i;
        char ch;
        System.out.println("Enter a string:");
        s = r.readLine()+" ";
        for(i=0;i < s.length();i++)
        {
            ch = s.charAt(i);
            if(ch!=' ')
            w=ch+w;
            else
            {
                s2 = s2+w+" ";
                w="";
            }
        }
        System.out.println("OutPut:"+s2);
    }
}