IQ

Ad SpeedyAds

Friday, March 9, 2012

Java program to print the words of a sentence in reverse

import java.io.*;
class abc
{
public static void main(Stringa aa[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a sentence");
String S=br.readLine();
S=S.trim();
S=" "+S+" ";
int L=S.length(),a=L;
for(int i=L-1; i>=0; i--)
{
if(S.charAt(i)==32)
{
System.out.print(S.substring(i+1,b)+" ");
b=i;
}
}
}
}

5 comments:

  1. There are some errors... I am trying to fix them.

    ReplyDelete
  2. Here is the corrected code....



    import java.io.*;

    class abc
    {

    public static void main(String aa[]) throws IOException
    {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter a sentence");
    String S = br.readLine();
    S = S.trim();
    S = " " + S + " ";
    int L = S.length(), a = L;
    for (int i = L - 1; i >= 0; i--)
    {
    if (S.charAt(i) == 32)
    {
    System.out.print(S.substring(i + 1, a) + " ");
    a = i;
    }
    }
    }
    }

    ReplyDelete
    Replies
    1. I am the corrector of the above code

      {my mail: voltaire101_5@yahoo.com}

      Delete
  3. better use the split() function in java.util (it is in course)
    [writing only the function]

    void invert(String a)
    {
    String b[] = a.split(" ");
    String c = " ";
    for (int i = b.length-1; i >= 0; i--)
    {
    c += b[i];
    if (i <= b.length-1) c += " ";
    }
    c = c.trim();
    System.out.println("The inverted string is: ");
    System.out.println(c);
    }

    ReplyDelete
  4. http://thecprojectt.blogspot.in for ISC JAVA Pgms and much more.

    ReplyDelete