Search This Blog

Sunday, December 12, 2010

STRING - To enter a string & display all its words in reverse individually

import java.io.*;
class revwords
{
    public static void main(String args[]) throws IOException
    {
        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter the string");
            String str=br.readLine();
            int i, a1, l,p,j;
            p=0;
            l=str.length();
            System.out.println("The original string is:    " +str);
            System.out.println("The string after reversing of words is : ");
            for(i=0; i<l; i++)
            {
                char a=str.charAt(i);
                a1=(int) a;
                if(a1==32||i==l-1)
                {
                    for(j=i; j>=p; j--)
                    {
                        char b=str.charAt(j);
                        System.out.print(b);
                    }
                    System.out.print(" ");
                    p=i;
                }
            }
    }
}     





OUTPUT:

Enter the string
yadavindra public school

The original string is:    yadavindra public school
The string after reversing of words is :
                                  ardnivaday  cilbup  loohcs 

1 comment:

  1. Alternatively you may skip the line
    a1=(int) a;

    and use this instead:
    if(a==' '||i==l-1)

    ReplyDelete