判断回文字符串

一、计思想判断一个字符串是否为回文字符串,运用循环结构从两端向中间比较各字符是否相等。

其中要将输入的字符串转化成字符数组,用到toCharArray()(将字符串对象中的字符转换为一个字符数组)。因为空字符也是回文字符,所以输入的字符串用nextLine()(返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的)。

二、程序流程图

 

 

三、源程序代码

package palindrome;

import java.util.Scanner;

public class palindrome

{

  public static void main(String[] args)

  {

    Scanner cin=new Scanner(System.in);

    char[] arr;

    String str;

    int i,j,len;

    System.out.println("请输入字符串:");

    str=cin.nextLine();

    arr=str.toCharArray();

    len=str.length();

    cin.close();

    for(i=0,j=len-1;i<=j;i++,j--)

    {

      if(arr[i]!=arr[j]) break;

    }

    if(i>j) System.out.println("输入的字符串是回文字符。");

    else System.out.println("输入的字符串不是回文字符。");

  }

}

 

四、结果截图

 

 

 

原文地址:https://www.cnblogs.com/cc-9878/p/7663078.html