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
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);
}
Here is a low level solution:
import java.util.Scanner;
public class class1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String inpStr = in.nextLine();
System.out.println("Original String :" + inpStr);
char temp;
char[] arr = inpStr.toCharArray();
int len = arr.length;
for(int i=0; i<(inpStr.length())/2; i++,len--){
temp = arr[i];
arr[i] = arr[len-1];
arr[len-1] = temp;
}
System.out.println("Reverse String :" + String.valueOf(arr));
}
}
Since the below method (using XOR) to reverse a string is not listed, I am attaching this method to reverse a string.
The Algorithm is based on :
1.(A XOR B) XOR B = A
2.(A XOR B) XOR A = B
Code snippet:
public class ReverseUsingXOR {
public static void main(String[] args) {
String str = "prateek";
reverseUsingXOR(str.toCharArray());
}
/*Example:
* str= prateek;
* str[low]=p;
* str[high]=k;
* str[low]=p^k;
* str[high]=(p^k)^k =p;
* str[low]=(p^k)^p=k;
*
* */
public static void reverseUsingXOR(char[] str) {
int low = 0;
int high = str.length - 1;
while (low < high) {
str[low] = (char) (str[low] ^ str[high]);
str[high] = (char) (str[low] ^ str[high]);
str[low] = (char) (str[low] ^ str[high]);
low++;
high--;
}
//display reversed string
for (int i = 0; i < str.length; i++) {
System.out.print(str[i]);
}
}
}
Output:
keetarp
public static String revString(String str){
char[] revCharArr = str.toCharArray();
for (int i=0; i< str.length()/2; i++){
char f = revCharArr[i];
char l = revCharArr[str.length()-i-1];
revCharArr[i] = l;
revCharArr[str.length()-i-1] = f;
}
String revStr = new String(revCharArr);
return revStr;
}
Take a look at the Java 6 API under StringBuffer
String s = "sample";
String result = new StringBuffer(s).reverse().toString();
Just For Fun..:)
Algorithm (str,len):
char reversedStr[] =new reversedStr[len]
Traverse i from 0 to len/2 and then
reversedStr[i]=str[len-1-i]
reversedStr[len-1=i]=str[i]
return reversedStr;
Time Complexity:O(n) Space Complexity :O(n)
public class Reverse {
static char reversedStr[];
public static void main(String[] args) {
System.out.println(reversestr("jatin"));
}
private static String reversestr(String str) {
int strlen = str.length();
reversedStr = new char[strlen];
for (int i = 0; i <= strlen / 2; i++) {
reversedStr[i] = str.charAt(strlen - 1 - i);
reversedStr[strlen - 1 - i] = str.charAt(i);
}
return new String(reversedStr);
}
}