Program to reverse a string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • abhishekphukan
    New Member
    • Jul 2014
    • 34

    Program to reverse a string

    Code:
    import java.util.*;
     
    class user{
       public static void main(String args[])
       {
          String original, reverse = "";
          Scanner in = new Scanner(System.in);
          System.out.println("Enter a string to reverse");
          original = in.nextLine();
          int length = original.length();
          for ( int i = length-1  ; i >= 0 ; i-- )
          reverse = reverse + original.charAt(i);
     
          System.out.println("Reverse of entered string    is:"    +reverse);
       }
    }
    can anyone explain why the length of the string is deducted by 1...The following line:

    for(int i-length-1;.....);

    Thank You.
    Last edited by Rabbit; Jan 5 '15, 04:50 PM. Reason: Please use [code] and [/code] tags when posting code or formatted data.
  • Exequiel
    Contributor
    • Jul 2012
    • 288

    #2
    its deducted by 1 because when we get the length of the letters of the input we need to convert it into char array, so the array counting starts at 0, so to get the reverse output of the input we loop it reversely and to be exact to the letters of our reverse string we deducted 1.
    example:
    Input: LOVE
    Output: EVOL
    Lenght of string input is 4.
    reversed counting for array inside the for loop starts at 3 and end to 0.
    so
    array[3] = E.
    array[2] = V.
    array[1] = O.
    array[0] = L.


    this is the sample code i made.

    Code:
    import java.io.*;
    
    public class palindrome
    {
    	public static void main(String [] args)
    	{
    	BufferedReader dataIn= new BufferedReader (new InputStreamReader(System.in));
    		
    		String reversed="";
    		String input="";
    		int x=0;
    		String sd="";
    				
    		try{
    
    			System.out.println("Input word to reverse and Determine If it is a palindrome or not! ");
    			input=dataIn.readLine();
    			 char toreverse[]=input.toCharArray();	
    
    			for(x=toreverse.length-(1); x>=0; x--)
    			{
    				reversed+=toreverse[x];	
    			}
    			System.out.println("Reverse of entered string is: "+reversed);
    
    		}catch (IOException e){
    			System.out.println("error!");}
    
    	}
    }

    Comment

    • abhishekphukan
      New Member
      • Jul 2014
      • 34

      #3
      Thnx a lot for clearifying it...:)
      i was just stuck at that line...thank you.

      Comment

      • Exequiel
        Contributor
        • Jul 2012
        • 288

        #4
        Your welcome. I'm glad to help. goodluck :)

        Comment

        Working...