I have \"Hello World\"
kept in a String variable named hi
.
I need to print it, but reversed.
How can I do this? I understand there
package logicprogram;
import java.io.*;
public class Strinrevers {
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter data");
String data=br.readLine();
System.out.println(data);
String str="";
char cha[]=data.toCharArray();
int l=data.length();
int k=l-1;
System.out.println(l);
for(int i=0;k>=i;k--)
{
str+=cha[k];
}
//String text=String.valueOf(ch);
System.out.println(str);
}
}
This did the trick for me
public static void main(String[] args) {
String text = "abcdefghijklmnopqrstuvwxyz";
for (int i = (text.length() - 1); i >= 0; i--) {
System.out.print(text.charAt(i));
}
}
public class Test {
public static void main(String args[]) {
StringBuffer buffer = new StringBuffer("Game Plan");
buffer.reverse();
System.out.println(buffer);
}
}
Here is an example using recursion:
public void reverseString() {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String reverseAlphabet = reverse(alphabet, alphabet.length()-1);
}
String reverse(String stringToReverse, int index){
if(index == 0){
return stringToReverse.charAt(0) + "";
}
char letter = stringToReverse.charAt(index);
return letter + reverse(stringToReverse, index-1);
}
You can use this:
new StringBuilder(hi).reverse().toString()
Or, for versions earlier than JDK 1.5, use java.util.StringBuffer
instead of StringBuilder
— they have the same API. Thanks commentators for pointing out that StringBuilder
is preferred nowadays when there is no concurrency concern.
All above solution is too good but here I am making reverse string using recursive programming.
This is helpful for who is looking recursive way of doing reverse string.
public class ReversString {
public static void main(String args[]) {
char s[] = "Dhiral Pandya".toCharArray();
String r = new String(reverse(0, s));
System.out.println(r);
}
public static char[] reverse(int i, char source[]) {
if (source.length / 2 == i) {
return source;
}
char t = source[i];
source[i] = source[source.length - 1 - i];
source[source.length - 1 - i] = t;
i++;
return reverse(i, source);
}
}