Results 1 to 4 of 4

Thread: Java - Reverse String using recursion

  1. #1

    Thread Starter
    Frenzied Member System_Error's Avatar
    Join Date
    Apr 2004
    Posts
    1,111

    Java - Reverse String using recursion

    This is a method I wrote using recursion to reverse a string. Recursions really not the best solution for anything, but this one turned out pretty cool.

    Code:
    public class ReverseString
    {
     public String reverse(String arg)
     {
    	String tmp = null;
    	if (arg.length() == 1)
    	{
    		return arg;
    	}
    	
    	else
    	{
    	
    		String lastChar = arg.substring(arg.length()-1,arg.length());
    		
    		String remainingString = arg.substring(0, arg.length() -1);
    
    		tmp = lastChar + reverse(remainingString);
    		return tmp;
    		
    		
    	}
      }
    }
    Code:
    import java.io.*;
    
    
    public class TestReverse
    {
    	public static void main(String[] args) throws IOException
     	{
    		System.out.println("Enter a line to be reversed");
    		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    		String inData;
    		inData = br.readLine();
    		ReverseString rs = new ReverseString();
    		System.out.println("Reversed: " + rs.reverse(inData));	
    	}
    }

  2. #2
    The Devil crptcblade's Avatar
    Join Date
    Aug 2000
    Location
    Quetzalshacatenango
    Posts
    9,091

    Re: Java - Reverse String using recursion

    Nice, but probably more efficient this way...
    Code:
    private static String reverseString(String s) 
    {
      return (new StringBuffer(s)).reverse().toString();
    }
    

    Laugh, and the world laughs with you. Cry, and you just water down your vodka.


    Take credit, not responsibility

  3. #3

    Thread Starter
    Frenzied Member System_Error's Avatar
    Join Date
    Apr 2004
    Posts
    1,111

    Re: Java - Reverse String using recursion

    Yes, but that isn't much fun.

  4. #4
    New Member
    Join Date
    Nov 2006
    Posts
    1

    Re: Java - Reverse String using recursion

    Just did this one. Enter text and recursion method will reverse it.

    Code:
     
    import java.util.Scanner;
    
    public class recursionDemo{
    
    	public static void main (String[] args){
    	
    		Scanner scan = new Scanner (System.in);
    		
    		System.out.println("Enter text to reverse: ");
    		String s = scan.nextLine();
    		reverse(s);
    		
    	}
    		
    	public static void reverse(String s){
    	
    		if (s.length() == 1){
    			System.out.print(s);
    		}
    		else{
    			 
    			reverse (s.substring(1, s.length()));  
    			System.out.print(s.substring(0,1));
    
    		}
    	}
    	
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width