1.回文是一种“从前向后读”和“从后向前读”都相同的字符串,如“上海自来水来自海上”。设计一个程序,判断字符串是否是回文。
代码:
package shiyan.shiyan8;
import java.util.Scanner;
public class HuiWenTest {
public static void main(String[] args) {
String str = "";
System.out.println("请输入一个字符串");
Scanner input = new Scanner(System.in);
str = input.next();
StringBuffer sb = new StringBuffer(str);
sb.reverse();// 将Str中的字符串倒置
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == sb.charAt(i)) {
count++;
}
}
if (count == str.length()) {
System.out.println("此字符串是一个回文字符串");
} else {
System.out.println("此字符串不是一个回文字符串");
}
}
}
倒置后判断若相同则为回文。