• Java 判断一段字符串是否是回文


     

     使用递归方式判断某个字串是否是回文:

     回文是指正着读、反着读都一样的句子。比如“我是谁是我”

    用到charAt()方法,例如下面的例子:charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1。

    语法:

    public char charAt(int index)

    参数

    • index -- 字符的索引。

    返回值

    返回指定索引处的字符。

    public class Test { public static void main(String args[]) {
            String s = "www.runoob.com";
            char result = s.charAt(8);
            System.out.println(result);
        }
    }

    以上程序执行结果为:

    o

     
     
    判断是否是回文,首先用户输入一段字符串,然后先判断字符串的长度,如果长度为零或一,则必是回文,若长度大于等于2,则先判断第一个字符与最后一个字符,相等则截取第二个到倒数第二个,再判断,利用递归方法。
    //源代码
    package lianxi1;
    import java.util.*;
    public class Palindrome {
     static public boolean isPa(String f,int n){
      
      if(f.charAt(0)==f.charAt(f.length()-1)) {
       if(f.length()>2) {
        return isPa(f.substring(n+1,f.length()-1),0); //从n+1到(f.length()-1)-1
       }
       else {
        return true;
       }
      }
      else return false;
      
     }
     public static void main(String[] args) {
      // TODO Auto-generated method stub
      Scanner scan = new Scanner(System.in);
      System.out.println("请输入字符串:");
      String f = scan.next();
      if(isPa(f,0)) {
       System.out.println("字符串: " + f + " 是回文串");
      }
      else {
       System.out.println("字符串: " + f + " 不是回文串");
      }
      
      
     }
    }
  • 相关阅读:
    Android 5.0新特性了解(一)----TabLayout
    Kafka生产者各种启动参数说明
    Kafka基础知识
    ONS发布订阅消息
    Spring异步事件
    Java动态代理机制
    Java线程间怎么实现同步
    技术架构实践三要点
    Distributed transactions in Spring, with and without XA
    Spring 中常用注解原理剖析
  • 原文地址:https://www.cnblogs.com/022414ls/p/11586577.html
Copyright © 2020-2023  润新知