简体   繁体   中英

JAVA String Reverse using StringBuilder

This code always returns false. What might be the problem ?

  public class S18_Palindrome {
      public static void main(String[] args) {
        String myString = new String("malayalam");
        if (myString.equals(new StringBuilder(myString).reverse())) {
          System.out.println("true");
        } else {
          System.out.println("false");
        }
      }
    }

问题是StringBuilder(myString).reverse()将返回您需要从中获取字符串值的StringBuilder对象。

new StringBuilder(myString).reverse().toString()

Got it :)

I had to convert the StringBuilder's value toString()

if (myString.equals(new StringBuilder(myString).reverse().toString()))

instead of

if (myString.equals(new StringBuilder(myString).reverse()))

Try this..

String s = "responses";
StringBuilder builder = new StringBuilder(s);
System.out.println(builder.reverse());

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