目前我正在试图用Java编写回文检查是不区分大小写。 我检查了其他主题,但没有一个似乎解决了我的问题。Java的回文检查 - 不区分大小写
这里是我的代码:
import java.util.Scanner;
public class Homework5_2 {
public static void main(String[] args) {
boolean flag = true; //palindrome or not
Scanner console = new Scanner(System.in);
System.out.print("Enter one or more words: ");
String s = console.next();
//checks if string contains spaces
if (s.matches(".*\\s+.*")) {
s = s.replaceAll("\\s+","");
}
s = s.toLowerCase();
int stringLength = s.length();
int index = 0;
//checks the string from both sides going towards the middle
for (int i=0;i<stringLength/2;i++) {
index = stringLength-i-1;
if (!(s.charAt(i) == s.charAt(index))) {
flag = false;
}
}
if (flag == true) {
System.out.println("The string is a palindrome!");
} else {
System.out.println("The string is not a palindrome!");
}
}
}
当进入像“操作系统,所以”,不正确的输出字符串,因为该字符串不是回文报道。 该问题似乎与空格有关,因为如果其中没有空格,则相同的字符串会正确报告为回文。 我真的有兴趣了解这段代码的缺陷,任何帮助将非常感谢!