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
热门推荐
10 病人祝福语老师寄语简短
11 新娘生孩子祝福语简短
12 婆婆66岁祝福语简短
13 今天孩子高考祝福语简短
14 送彩票生日祝福语简短
15 分别祝福语简短情话英文
16 画室揭牌仪式祝福语简短
17 女友妈妈生日祝福语简短
18 离别赠言离职祝福语简短