我以为反向应该等于“ tor”,但是当我尝试

String straight = stringBuilders[i].toString();
String reverse = stringBuilders[i].reverse().toString();
System.out.println("stringBuilders[i].reverse().toString() = " +  stringBuilders[i].reverse().toString()
+ " reverse = " + reverse + "    straight = " + straight +
" rev == str ? " + reverse.equals(straight));


我得到了这样的结果

stringBuilders[i].reverse().toString() = rot, reverse = tor, straight = tor, rev == str? false


为什么?

rev == str ?输出为false
怎么会这样

stringBuilders[i].reverse().toString() = rot, reverse = tor,

最佳答案

您的第一个问题可能是straight使用索引j,而其余代码使用索引i

这是您作为MCVE(Minimal, Complete, and Verifiable example)的代码:

StringBuilder stringBuilder = new StringBuilder("tor");
String straight = stringBuilder.toString();
String reverse = stringBuilder.reverse().toString();
System.out.println("stringBuilders[i].reverse().toString() = " +  stringBuilder.reverse().toString() +
                   " reverse = " + reverse +
                   "    straight = " + straight +
                   " rev == str? " + reverse.equals(straight));


输出为:

stringBuilders[i].reverse().toString() = tor reverse = rot    straight = tor rev == str? false


那不是您显示的输出。

无论如何,您的主要问题是reverse()


  使此字符序列被序列的相反字符替换。


因此,第一次调用reverse()会使stringBuilder具有值rot,这也是分配给reverse变量的值。

您在print语句中第二次调用reverse()会将其还原为值tor,然后再打印该值。

关于java - stringBuilder.reverse如何工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37097204/

10-13 03:21