java字符串回文_Java程序检查字符串为回文

如果即使反向将每个字符的位置都保持不变,则字符串为回文字符串。例如,``MADAM''是回文字符串,因为即使反向将字符串``MADAM''也使每个字符的位置保持不变。作为回文与否,我们可以使用库方法,也可以不使用库方法。

但是,如果我们要检查“女士”是否是回文,则由于首字母大写,它会告诉我们它不是回文。

示例-没有库方法。public class Palindrome {

public static void main(String[] args) {

String str = "SATYA";

StringBuffer newStr =new StringBuffer();

for(int i = str.length()-1; i >= 0 ; i--) {

newStr = newStr.append(str.charAt(i));

}

if(str.equalsIgnoreCase(newStr.toString())) {

System.out.println("String is palindrome");

} else {

System.out.println("String is not palindrome");

}

}

}

输出结果String is not palindrome

示例-使用库方法。public class Palindrome {

public static void main (String[] args) throws java.lang.Exception {

String str = "NITIN";

String reverse = new StringBuffer(str).reverse().toString();

if (str.equals(reverse))

System.out.println("String is palindrome");

else

System.out.println("String is not palindrome");

}

}

输出结果String is palindrome

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值