开发者

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

开发者 https://www.devze.com 2023-04-09 08:57 出处:网络
Is it possible to reverse S开发者_如何学Pythontring in Java without using any of the temporary variables like String, Char[] or StringBuilder?

Is it possible to reverse S开发者_如何学Pythontring in Java without using any of the temporary variables like String, Char[] or StringBuilder?

Only can use int, or int[].


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.


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


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


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


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

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

}


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.


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

}


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


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


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.


You can use class java.lang.StringBuilder:

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

精彩评论

暂无评论...
验证码 换一张
取 消