Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a string in Java

Tags:

java

string

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 is some kind of a function already built-in into Java that does that.

Related: Reverse each individual word of “Hello World” string with Java

like image 968
Ron Avatar asked Sep 27 '11 12:09

Ron


People also ask

What is the logic for reversing string in Java?

{ public static void main(String[] args) { String string = "Dream big"; //Stores the reverse of given string.

What Reverse () will do in Java?

To reverse a string in java, we can first convert it to StringBuilder which is nothing but a mutable string. Class StringBuilder provides an inbuilt function called reverse(), which reverses the given string and provides you with the final output.


2 Answers

You can use this:

new StringBuilder(hi).reverse().toString() 

StringBuilder was added in Java 5. For versions prior to Java 5, the StringBuffer class can be used instead — it has the same API.

like image 131
Daniel Brockman Avatar answered Oct 13 '22 08:10

Daniel Brockman


For Online Judges problems that does not allow StringBuilder or StringBuffer, you can do it in place using char[] as following:

public static String reverse(String input){     char[] in = input.toCharArray();     int begin=0;     int end=in.length-1;     char temp;     while(end>begin){         temp = in[begin];         in[begin]=in[end];         in[end] = temp;         end--;         begin++;     }     return new String(in); } 
like image 36
Sami Eltamawy Avatar answered Oct 13 '22 07:10

Sami Eltamawy