Dark Horse Programmer_Determine whether a string is a symmetrical string

------- android training , java training , looking forward to communicating with you! ----------


 

Determine whether a string is a symmetric string? I just saw such a question, and thought it was very simple, and it is indeed the case, so how to complete this question? ? ?

First of all, we need to make it clear that since we are judging the symmetry of the string, we must first judge whether the characters in the relative position match? If it matches, return a TRUE, otherwise return FALSE, then the problem is solved! Of course, there are many ways to solve this problem, but I mainly complete it from the following ideas:

1. Convert the string to a character array

2. Use the for loop to traverse the judging character array, if the relative positions match each other, return TRUE, otherwise FALSE ---------> (this step is the key)

3. Enter a character string to complete the test

 

The relevant code is as follows:

package com.itheima;

import java.util.Scanner;

/**
 *Determine whether a string is a symmetrical string, for example, "abc" is not a symmetrical string, "aba", "abba", "aaa", "mnanm" are symmetrical strings* @author Huang Xianheng
 *
 *
 /
public class Test4 {

 /**
  * @param args
  */
 public static void main(String[] args) {

 

  //Instantiate Scanner object
  Scanner s=new Scanner(System.in);
  //Print prompt
  System.out.println("Please enter a string");
  //Input string
  String str=s.next();
  
  System.out.println(str+"Is it symmetrical?"+isSymmetry(str));
 }
 //Create a method that can receive a string as a parameter, and encapsulate whether the parameter is a symmetrical string in the method. If so, Return TRUE, otherwise return FALSE
 public static boolean isSymmetry(String str){   //Convert the string into a character array   char[]ch=str.toCharArray();   //Loop to determine whether the character array is consistent before and after   for(int x= 0;x<ch.length;x++){    if(ch[x]!=ch[ch.length-x-1]){     return false;    }   }   return true;  }









}

After completing this question, I found that the conversion between strings and character arrays is also commonly used. The format of converting a string to a character array is: string.toCharArray(). After understanding this question, I found that we can also use this It can be said to use the thought of the problem to complete the judgment of the number of palindrome, etc. ! !

 

------- android training , java training , looking forward to communicating with you! ----------

 

For details, please check: http://edu.csdn.net/heima

Guess you like

Origin blog.csdn.net/huangxuanheng/article/details/38057907