zoukankan      html  css  js  c++  java
  • 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 + " 不是回文串");
      }
      
      
     }
    }
  • 相关阅读:
    JQuery图片预览
    1.数组
    1.什么是C++
    安装PHPCMS 遇到的问题(fsockpen)
    解决采集时提示”没有找到网址列表,请先进行网址采集“的问题
    JAVA 常用的网站
    页面静态化
    我的C笔记系列一
    PHP缓存技术
    PHPCMS 采集规则
  • 原文地址:https://www.cnblogs.com/022414ls/p/11586577.html
Copyright © 2011-2022 走看看