Tuesday 5 February 2013

Reverse a string in java


public class ReverseString {

      public static void main(String[] args) {
            String word = "Hai this is karthik";
            word = new StringBuffer(word).reverse().toString();
            System.out.println(word);

      }

}



Output:

             kihtrak si siht iaH





import java.util.*;

class ReverseString
{
   public static void main(String args[])
   {
      String reverse ="";
      System.out.println("Enter the String");
      Scanner scan = new Scanner(System.in);
      String  original = scan.nextLine();

      int length = original.length();

      for ( int i = length - 1 ; i >= 0 ; i-- )
         reverse = reverse + original.charAt(i);

      System.out.println("Reverse string is: "+reverse);
   }
}


Output:

Enter the String
hai this is karthik
Reverse string is: kihtrak si siht iah


Using StringTokenizer word by word 



   import java.util.StringTokenizer;

public class ReverseLine {

      public static void main(String[] args) {

            String word = "Java Reverse String";
            StringTokenizer st = new StringTokenizer(word, " ");
            String stringReversedLine = "";

            while (st.hasMoreTokens()) {
                  stringReversedLine = st.nextToken() + " " + stringReversedLine;
            }

            System.out.println("Reversed string by word :" + stringReversedLine);
      }
}

Output:

                   Reversed string is : String Reverse Java 


     







No comments:

Post a Comment