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[].

11
  • 14
    Is this homework? Wouldn't using int or int[] constitute temporaries? Commented Sep 30, 2011 at 15:11
  • 2
    java2s.com/Code/Java/Language-Basics/ReverseStringTest.htm Commented Sep 30, 2011 at 15:11
  • Any method that reverses a string would have to rely on temporary information, whether or not it's encapsulated away. Commented Sep 30, 2011 at 15:12
  • @Eng.Fouad: he said he can't have StringBuffers or such like Commented Sep 30, 2011 at 15:13
  • 1
    @kaibuki You want to ask candidates an interview question that you couldn't answer? Commented Sep 30, 2011 at 15:56

11 Answers 11

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.

Sign up to request clarification or add additional context in comments.

Comments

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));
}

Comments

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! :)

Comments

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);

Comments

2
public String reverseStr(String str) {
    if (str.length() <= 1) {
        return str;
    }

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

}

Comments

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.

Comments

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);
    }

}

Comments

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 :)

Comments

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));
}
}

Comments

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.

Comments

-1

You can use class java.lang.StringBuilder:

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

2 Comments

the OP said without StringBuilder
The question says without using StringBuilder library

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.