Java - to determine whether a string is a palindrome

First, the palindrome refers to a form similar to "12345", "abcdcba", that is mindfulness and anti-concept is the same string

To determine whether a string is a palindrome, here describes three kinds of way

  1. Flip string, determining whether or not the inversion is equal to the original string and the string
    . 1  public  static  void main (String [] args) {
     2      String S = "abcdcba" ;
     . 3      // StringBuilder by reverse method will reverse a string 
    . 4      StringBuilder SB = new new StringBuilder (S);
     . 5      String afterReverse = sb.reverse () .toString ();
     . 6      // after inversion determination character string is equal to the original string, can be the compareTo, the equals, 
    . 7      int isEqual = afterReverse.compareTo (S);   // if the output is equal to 0 
    . 8      iF ( == 0 isEqual ) {
     . 9          System.out.println ( "palindromic" );
     10      } the else 
    . 11         System.out.println ( "not a palindrome" );
     12 }

    Note: compareTo, equals judge strings are considered sensitive, ie sensitive deemed not want to wait, if necessary without regard to case, you can use equalsIgnoreCase

  2. loop for sequentially determining whether the corresponding character is equal to
    . 1      public  static  void main (String [] args) {
     2          String S = "12,344,321" ;
     . 3          int L = s.length ();
     . 4          System.out.println (L / 2 );
     . 5          int Result =. 1 ;
     . 6          / / start comparison to both sides from the intermediate 
    . 7          for ( int I = 0; I <L / 2; I ++ ) {
     . 8              IF (s.charAt (I) == s.charAt (Li-. 1 )) {
     . 9                  Result = 0 ;
     10              } the else {
     . 11                  Result =. 1 ;
    12 is                  BREAK ;   // need not want to wait out a comparison cycle time, or as long as the last established a comparison, returns 0 = Result 
    13 is              }
     14          }
     15          IF (Result == 0 ) {
     16              System.out.println ( "yes palindrome " );
     . 17          } the else {
     18 is              System.out.println (" not a palindrome " );
     19          }
     20      }
  3. Other be added, for example, the string from the intermediate resolution, and then comparison,

Guess you like

Origin www.cnblogs.com/mysummary/p/12340915.html