Reverse String in Java without using any Temporary String,Char or String Builder
Asked Answered
A

11

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

Anet answered 30/9, 2011 at 15:8 Comment(11)
Is this homework? Wouldn't using int or int[] constitute temporaries?Mcminn
java2s.com/Code/Java/Language-Basics/ReverseStringTest.htmJigsaw
Any method that reverses a string would have to rely on temporary information, whether or not it's encapsulated away.Vertex
@Eng.Fouad: he said he can't have StringBuffers or such likeRosemare
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.Anet
@birryree, int or int [] cant store String/Char. we can use data types which don't store sting/charAnet
@Eng.Fouad, string buffer is again the same thing :)Anet
I think this one's been hammered to death, e.g., on CodeMonkey. An int[] is just a different flavor of temporary.Clemmy
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.Tientiena
@kaibuki You want to ask candidates an interview question that you couldn't answer?Hordein
#29050810Toad
A
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.

Asthenic answered 30/9, 2011 at 15:24 Comment(1)
This is brilliant !! Thanks for the perspective!Rositaroskes
B
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));
}
Barkley answered 30/9, 2011 at 15:16 Comment(0)
J
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! :)

Jigsaw answered 30/9, 2011 at 15:21 Comment(0)
I
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);
Inexpressive answered 30/9, 2011 at 15:23 Comment(0)
K
2
public String reverseStr(String str) {
    if (str.length() <= 1) {
        return str;
    }

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

}
Kinnard answered 2/2, 2015 at 12:40 Comment(0)
W
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.

Wolfie answered 30/9, 2011 at 15:21 Comment(0)
L
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);
    }

}
Lubberly answered 2/2, 2015 at 6:31 Comment(0)
J
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 :)

Junie answered 26/9, 2016 at 11:8 Comment(0)
E
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));
}
}
Elflock answered 17/5, 2017 at 11:3 Comment(0)
F
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.

Feaze answered 23/1, 2018 at 10:6 Comment(0)
Y
-1

You can use class java.lang.StringBuilder:

String reservedString = new StringBuilder(str).reserve().toString();
Yager answered 15/5, 2013 at 22:59 Comment(2)
the OP said without StringBuilderTrow
The question says without using StringBuilder libraryMnemonics

© 2022 - 2024 — McMap. All rights reserved.