我正在尝试创建一个名为“palindrome”的方法,该方法接收一个字符串,如果该字符串是回文,则返回一个 boolean 值 true,如果不是,则返回 false。如果一个单词向前和向后读起来相同,那么它就是回文。例如,单词 level 是回文。
例如,考虑通过删除所有空格和标点符号并将所有字母转换为小写形式获得的文本作为回文:
女士,我是亚当==>女士
一个人,一个计划,一条运河:巴拿马 ==> amanaplanacanalpanama
我尝试处理我使用的代码 replaceAll();
并输出为替换全部的最后一行。
public static String palindrome(String n){
char[] input = n.toCharArray();
//for(int i=0; i<input.length; i++){ //looping reversing using input as in length minus 1 from end to start and counting using increment
n.toLowerCase();
String noSpaces = n.replaceAll(" ", ""); //I used this to get string
String remove = noSpaces.replaceAll(",","");
String remove2 = remove.replaceAll(".","");
String remove3 = remove2.replaceAll(":","");
String remove4 = remove3.replaceAll("!", "");
System.out.print(remove4);
//return n;
//}
return n;
}
编译器/输出:
Input: Madam, I'm Adam
Output:
输出没有显示任何内容?我究竟做错了什么?
最佳答案
问题是点本质上可以匹配任意字符任意次数。因此,如果您输入 remove.replaceAll(".","")
所有字符都会被替换为空。您应该转义点以指定实际的点。希望这会有所帮助。
n = n.toLowerCase();//you should assign the result to get lowercase characters
String noSpaces = n.replaceAll(" ", ""); //I used this to get string
String remove = noSpaces.replaceAll(",","");
String remove2 = remove.replaceAll("\\.","");
String remove3 = remove2.replaceAll(":","");
String remove4 = remove3.replaceAll("!", "");
String remove5 = remove2.replaceAll("\'","");//you should also escape apostrophe
System.out.print(remove5);
关于java - JAVA中使用字符串的回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60500062/