7

Is it possible to reverse String in Java without using any of the temporary variables like String, Char[] or StringBuilder?

Only can use int, or int[].

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Adil Bhatty
  • 17,190
  • 34
  • 81
  • 118
  • 14
    Is this homework? Wouldn't using `int` or `int[]` constitute temporaries? – wkl Sep 30 '11 at 15:11
  • 2
    http://www.java2s.com/Code/Java/Language-Basics/ReverseStringTest.htm – Eng.Fouad Sep 30 '11 at 15:11
  • Any method that reverses a string would have to rely on temporary information, whether or not it's encapsulated away. – DJ Quimby Sep 30 '11 at 15:12
  • @Eng.Fouad: he said he can't have StringBuffers or such like – Aleks G Sep 30 '11 at 15:13
  • Its not homework, its just something came into my mind to ask candidate for job interview question, I myself is working on how to do it without temp variables. – Adil Bhatty Sep 30 '11 at 15:17
  • @birryree, int or int [] cant store String/Char. we can use data types which don't store sting/char – Adil Bhatty Sep 30 '11 at 15:18
  • @Eng.Fouad, string buffer is again the same thing :) – Adil Bhatty Sep 30 '11 at 15:19
  • I think this one's been hammered to death, e.g., on [CodeMonkey](http://codemonkeyism.com/java-interview-questions-write-a-string-reverser-and-use-recursion/). An int[] is just a different flavor of temporary. – Ed Staub Sep 30 '11 at 15:22
  • Create a JNI call, passing the string into the C function, and then get a pointer to the char * from the jstring struct, and then you can reverse the char * in place. No use of other classes or indeed object creation necessary. May not be exactly what is required though. – Matthew Farwell Sep 30 '11 at 15:25
  • 1
    @kaibuki You want to ask candidates an interview question that you couldn't answer? – Jim Sep 30 '11 at 15:56
  • http://stackoverflow.com/questions/29050310/java-reverse-string-without-temp-string-array-stringbuilder-substring – hossein ketabi Sep 08 '15 at 07:04

11 Answers11

11
String reverseMe = "reverse me!";
for (int i = 0; i < reverseMe.length(); i++) {
    reverseMe = reverseMe.substring(1, reverseMe.length() - i)
        + reverseMe.substring(0, 1)
        + reverseMe.substring(reverseMe.length() - i, reverseMe.length());
 }
 System.out.println(reverseMe);

Output:

!em esrever

Just for the fun of it, of course using StringBuffer would be better, here I'm creating new Strings for each Iteration, the only difference is that I'm not introducing a new reference, and I've only an int counter.

stivlo
  • 83,644
  • 31
  • 142
  • 199
10

The objects of the Java String class are immutable - their contents cannot be altered after being created.

You will need at least two temporary objects - one for the final result and one for the intermediate values - even if you do find a way to avoid using a local variable.

EDIT:

That said, since you can use int[] you may be able to cheat.

Since char can be assigned to int, you can use String.charAt() to create an int array with the character values in reverse order. Or you may be allowed to use String.toCharArray() to get a char array that will be copied over to your int[] temporary.

Then you use the variable that holds the reference to your original string (or the result variable, if you are allowed one) to start from an empty string (easily obtainable with a direct assignment or String.substring()) and use String.concat() to create the final result.

In no case, however, will you be able to swap the characters in-place as you would do in C/C++.

EDIT 2:

Here's my version which does not use StringBuffer/Builders internally:

int r[] = new int[s.length()];

int idx = r.length - 1;

for (int i : s.toCharArray()) {
    r[idx--] = i;
}

s = s.substring(0, 0);

for (int i : r) {
    s = s.concat(String.valueOf((char)i));
}
thkala
  • 84,049
  • 23
  • 157
  • 201
5
String s = "Hello World!";
for(int i = 0; i < s.length(); i++)
{
    s = s.substring(1, s.length() - i) + s.charAt(0) + s.substring(s.length() - i);
}
System.out.println(s); // !dlroW olleH

No temporary variables! :)

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
5

One of many ways:

    String str = "The quick brown fox jumps over the lazy dog";

    int len = str.length();
    for (int i = (len-1); i >= 0; --i) 
        str += str.charAt(i);
    str = str.substring(len);

    System.out.println(str);
claymore1977
  • 1,385
  • 7
  • 12
2
public String reverseStr(String str) {
    if (str.length() <= 1) {
        return str;
    }

    return reverseStr(str.substring(1)) + str.charAt(0);

}
Vivek Mishra
  • 1,772
  • 1
  • 17
  • 37
1

First append the string to itself in reverse manner. Then take the second half out of it.

  public class RevString {
    public static void main(String[] args) {
        String s="string";
        for(int i=s.length()-1;i>=0;i--){
            s+=s.charAt(i);
        }
        s=s.substring(s.length()/2, s.length());
        System.out.println(s);
    }

}
Praveen Kumar
  • 1,624
  • 5
  • 18
  • 21
1

Because you can use an int, you can assign an int a char value:

String aString = "abc";

int intChar = aString.charAt(0);

You will have to convert from the int back to the char to assign it to aString.charAt(2).

I'm sure you can figure it out from there.

0

Without using any collection,StringBulider, StringBuffer or temp array reverse the string. Simple and crisp:

public static void main(String[] args) {

    String test = "Hello World";
    String rev = "";
    Pattern p = Pattern.compile("[\\w|\\W]");
    Matcher m = p.matcher(test);
    while (m.find()) {
        rev = m.group()+rev;
    }
    System.out.println("Reverse==" + rev);
}

Output

Reverse==dlroW olleH

Hope it helps :)

I_Tech_Avi
  • 23
  • 4
0
public class Test {
 static St`enter code here`ring reverseString(String str) {
    for (int i = 0; i < str.length() / 2; i++) {
        if (i == 0) {
            str = str.charAt(str.length() - 1 - i) + str.substring(i + 1, str.length() - 1 - i) + str.charAt(i);
        } else {
            str = str.substring(0, i) + str.charAt(str.length() - 1 - i)
                    + str.substring(i + 1, str.length() - 1 - i) + str.charAt(i)
                    + str.substring(str.length() - i, str.length());
        }
    }
    return str;
}

public static void main(String args[]) {

    String s = "ABCDE";
    System.out.println(Test.reverseString(s));
}
}
Robert
  • 5,278
  • 43
  • 65
  • 115
0
String str = "Welcome";
for(int i=0;i<str.length();){
  System.out.print(str.charAt(str.length()-1));
  str = str.substring(0,str.length()-1);
}

Except for loop variables.

Mani Kasi
  • 240
  • 1
  • 2
  • 16
-1

You can use class java.lang.StringBuilder:

String reservedString = new StringBuilder(str).reserve().toString();