判断一句话中开头与结尾处字符是否相同
import java.util.Scanner; public class TestPalindrome { public static void main(String[] args) { // TODO Auto-generated method stub //use the scanner function to input a sentence System.out.println("input a sentence"); Scanner input = new Scanner(System.in); String inStr = input.nextLine(); //Convert uppercase words in sentences to lowercase //translate the sentence into a Array
String sentence=inStr.toLowerCase();将一句话中的字母全部转化为小写 char[] elements = sentence.toCharArray(); 将这句话转化为数组的形式(也可以直接声明的一个数组将输入的句子储存进去) //read the first characters and the last characters of the sentence char firstChara=elements[0]; char lastChara; int i=1; //make sure that the last character is a letter not others
这一步就是从后往前读取数组中的内容,并判断是否为字符 do { lastChara=elements[elements.length-i]; i++; }while(!Character.isLetter(lastChara)); /** * compare first character and last character */ if(firstChara==lastChara) { System.out.println("this sentence is a palindromic sentences"); } else{ System.out.println("this sentence is not a palindromic sentences"); } } }