简体   繁体   中英

Why does this reversed StringBuilder not equal the original String when checking for a Palindrome?

I am trying to create a function that takes in a String 's' to check if it is a Palindrome:

    StringBuilder sb = new StringBuilder();
    
    for (char c : s.toCharArray()) {
        if (Character.isLetterOrDigit(c)) {
            sb.append(Character.toUpperCase(c));
        }
    }
    
    return sb.toString().equals(sb.reverse().toString());

For some reason if I change the return statement to this, it returns true instead of false for certain non palindromes:

return sb.reverse().toString().equals(sb.toString());

I'm not sure why changing the order of the reverse would cause this.

It happens because reverse() changes StringBuilder and then returns this :

return sb.toString()                         // "12345", sb -> "12345"
         .equals(
                 sb.reverse().toString()     // "54321", sb -> "54321"
                );                           // false

return sb.reverse().toString()               // "54321", sb -> "54321"
         .equals(
                 sb.toString()               // "54321", sb -> "54321"
                );                           // true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM