Reverse the string without using any temporary variable?
1. We can use XOR logic for swapping the variables.
public String reverseString(String str)
{
char[] a = str.toCharArray();
int len = a.length-1;
int half = a.length/2;
for (int i = 0; i < half; i++)
{
return String.valueOf(a);
}
2. Using built-in reverse() method of the StringBuilder class.
public String reverseString(String str)
{
char[] a = str.toCharArray();
int len = a.length-1;
int half = a.length/2;
for (int i = 0; i < half; i++)
{
a[i] ^= a[len - i];
a[len - i] ^= a[i];
a[i] ^= a[len - i];
} return String.valueOf(a);
}
2. Using built-in reverse() method of the StringBuilder class.
public void reverseString(String input)
{
StringBuilder input1 = new StringBuilder();
// append a string into StringBuilder input1
input1.append(input);
// reverse StringBuilder input1
input1 = input1.reverse();
// print reversed String
for (int i=0; i<input1.length(); i++)
System.out.print(input1.charAt(i));
}
Comments
Post a Comment