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
{ public static void main(String[] args) { String string = "Dream big"; //Stores the reverse of given string.
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With