在Java中反转字符串而不使用任何临时字符串、字符或字符串生成器

发布于 2024-12-07 17:09:37 字数 179 浏览 0 评论 0原文

是否可以在不使用 StringChar[]StringBuilder 等临时变量的情况下反转 Java 中的 String >?

只能使用intint[]

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

停顿的约定 2024-12-14 17:09:37
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);

输出:

!em esrever

只是为了好玩,当然使用 StringBuffer 会更好,这里我为每个迭代创建新的字符串,唯一的区别是我没有引入新的引用,并且我只有一个 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.

玻璃人 2024-12-14 17:09:37

Java String 类的对象是不可变的 - 它们的内容在创建后不能更改。

您将需要至少两个临时对象 - 一个用于最终结果,另一个用于中间值 - 即使您确实找到了一种避免使用局部变量的方法。

编辑:

也就是说,既然你可以使用 int[] 你也许可以作弊。

由于 char 可以分配给 int,因此您可以使用 String.charAt() 创建一个 int 数组,其中字符值按相反顺序排列。或者,您可以使用 String.toCharArray() 来获取 char 数组,该数组将被复制到您的 int[] 临时数组中。

然后,您使用保存对原始字符串(或结果变量,如果允许的话)的引用的变量从空字符串开始(可以通过直接赋值或 String.substring() 轻松获得) >) 并使用 String.concat() 创建最终结果。

然而,在任何情况下,您都无法像在 C/C++ 中那样就地交换字符。

编辑2:

这是我的版本,内部不使用 StringBuffer/Builders:

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

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));
}
-残月青衣踏尘吟 2024-12-14 17:09:37
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

没有临时变量! :)

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

转角预定愛 2024-12-14 17:09:37

多种方法之一:

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

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);
小…楫夜泊 2024-12-14 17:09:37
public String reverseStr(String str) {
    if (str.length() <= 1) {
        return str;
    }

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

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

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

}
流云如水 2024-12-14 17:09:37

因为可以使用 int,所以可以为 int 分配 char 值:

String aString = "abc";

int intChar = aString.charAt(0);

您必须将 int 转换回 char,才能将其分配给 aString.charAt(2)。

我相信你可以从那里弄清楚。

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.

黎夕旧梦 2024-12-14 17:09:37

首先以相反的方式将字符串附加到自身。然后把后半部分拿出来。

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

}

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

}
丿*梦醉红颜 2024-12-14 17:09:37

不使用任何集合、StringBulider、StringBuffer 或临时数组反转字符串。简单明快:

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

输出

反向==dlroW olleH

希望有帮助:)

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

潇烟暮雨 2024-12-14 17:09:37
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));
}
}
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));
}
}
抱着落日 2024-12-14 17:09:37
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);
}

循环变量除外。

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.

楠木可依 2024-12-14 17:09:37

您可以使用类 java.lang.StringBuilder:

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

You can use class java.lang.StringBuilder:

String reservedString = new StringBuilder(str).reserve().toString();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文