集册 Java实例教程 测试回文字符串

测试回文字符串

欢马劈雪     最近更新时间:2020-01-02 10:19:05

643
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
测试回文字符串

public class Main {

  public static void main(String[] args) {/* 来自 N o w  J a v a  . c o m*/

    String str1 = "hello";

    boolean b1 = Main.isPalindrome(str1);

    System.out.println(str1 + " is a palindrome: " + b1 );


    String str2 = "noon";

    boolean b2 = Main.isPalindrome(str2);

    System.out.println(str2 + " is a palindrome: " + b2 );

  }


  public static boolean isPalindrome(String inputString) {

    // Check for null argument. 

    if (inputString == null) {

      throw new IllegalArgumentException("String cannot be null.");

    }

    // Get the length of string 

    int len = inputString.length();//nowjava.com - 时代Java 提 供

    if (len <= 1) {

      return true;

    }


    // Convert the string into uppercase, so we can make the comparisons case insensitive 

    String newStr = inputString.toUpperCase();


    // Initialize the result variable to true 

    boolean result = true;


    // Get the number of comparison to be done 

    int counter = len / 2;


    for (
展开阅读全文