方式一
public static String judge(String str) {
int m = 0;
int k = str.length() - 1;
while (m < k) {
if (str.charAt(m) != str.charAt(k)) {
return "字符串不是回文";
}
m++;
k--;
}
return "字符串是回文";
}
public static void main(String[] args) {
String str = "上海自来水来自海上";
System.out.println(judge(str));
}
方式二
public static void main(String[] args) {
String str = "上海自来水来自海上";
int m = 0;
int k = str.length() - 1;
boolean judge = true;
while (m < k) {
if (str.charAt(m) != str.charAt(k)) {
judge = false;
break;
}
m++;
k--;
}
System.out.println(judge?"字符串是回文":"字符串不是回文");
}
方式三
public static void main(String[] args) {
String str = "上海自来水来自海上";
int judge = 0;
for (int k = 0; k < str.length() / 2; k++) {
if (str.substring(k, k + 1).equals(str.substring(
str.length() - k - 1, str.length() - k) )) {
judge++;
}
}
System.out.println((judge == str.length() / 2)?"字符串是回文":"字符串不是回文");
}