package com.itheima;
public class Test2
{
/**
* 第2题:判断一个字符串是否是对称字符串,例如"abc"不是对称字符串,"aba"、"abba"、"aaa"、"mnanm"是对称字符串
*
* 思路:对称字符串的特性是第一个字符与最后一个字符相同,第二个字符与倒数第二个字符相同,以此类推。
* 用String类的charAt()方法来获取字符串的每个位置上的字符,用for循环遍历字符串来进行比较。
* @param args
*/
public static void main(String[] args)
{
//定义一个字符串变量
String str = "abcdcba";
method(str);
str = "abccba";
method(str);
str = "abcdca";
method(str);
}
public static void method(String str)
{
//获取字符串的长度
int len = str.length();
//用for循环,比较前后每对字符
for (int i = 0; i <= len/2; i++)
{
//如果相等,则继续比较下一对
if(str.charAt(i) == str.charAt(len-i-1))
{
//如果i == len/2,遍历完成,该字符串是对称字符串
if(i == len/2)
System.out.println(str + "是对称字符串");
//如果i != len/2,继续for循环。
else
continue;
}
//字符串中前后任意一对字符不相等,则该字符串是不对称字符串,直接退出for循环
else
{
System.out.println(str + "不是对称字符串");
break;
}
}
}
}
|
|