-
Jan 19th, 2005, 07:22 PM
#1
Thread Starter
Frenzied Member
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));
}
}
-
Jan 26th, 2005, 07:36 AM
#2
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
-
Jan 26th, 2005, 03:22 PM
#3
Thread Starter
Frenzied Member
Re: Java - Reverse String using recursion
Yes, but that isn't much fun.
-
Nov 28th, 2006, 10:51 PM
#4
New Member
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|