Skip to content
Advertisement

How work stringBuilder.reverse?

I thought revers should be equal “tor”, but when I tried

JavaScript

I got such result

JavaScript

Why?

rev == str ? gives output as false How can be that

JavaScript

Advertisement

Answer

Your first problem might be that straight uses index j, while the rest of the code uses index i.

Here is your code as an MCVE (Minimal, Complete, and Verifiable example):

JavaScript

Output is:

JavaScript

That is not the output you showed.

Anyway, your main problem is that reverse():

Causes this character sequence to be replaced by the reverse of the sequence.

So, your first call to reverse() makes the stringBuilder have the value rot, which is also the value assigned to the reverse variable.

Your second call to reverse() in the print statement reverse it back to the value tor, which is then the value printed.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement