我有程序编写,直到它必须忽略和线程中的标点和空格,我想知道是否有人可以帮我编码?我一直在尝试的东西似乎没有起作用.这是我到目前为止:
import java.util.Scanner;
public class PalindromeTester
{
public static void main (String[] args)
{
String str, another = "y";
int left, right;
char charLeft, charRight;
Scanner scan = new Scanner (System.in);
while (another.equalsIgnoreCase("y")) // allows y or Y
{
System.out.println ("Enter a potential palindrome: ");
str = scan.nextLine();
left = 0;
right = str.length() - 1;
while (left < right)
{
charLeft = str.charAt(left);
charRight = str.charAt(right);
if (charLeft == charRight)
{
left++;
right--;
}
else if (charLeft == ',' || charLeft == '.' ||
charLeft == '-' || charLeft == ':' ||
charLeft == ';' || charLeft == ' ')
left++;
else if (charRight == ',' || charRight == '.' ||
charRight == '-' || charRight == ':' ||
charRight == ';' || charRight == ' ')
right--;
else
break;
}
System.out.println();
if (left < right)
System.out.println ("That string is NOT a palindrome.");
else
System.out.println ("That string IS a palindrome.");
System.out.println();
System.out.print ("Test another palindrome (y/n)? ");
another = scan.nextLine();
}
}
}Run Code Online (Sandbox Code Playgroud)
只是为了澄清Jim Garrison所说的,你需要的正则表达式如下
String m = "Madam, I'm'',.,.'' Adam";
m = m.toLowerCase().replaceAll("\\W", "");
Run Code Online (Sandbox Code Playgroud)
这将只留下字母和数字,并删除空格和标点符号,即m将成为"madamimadam",你可以对该字符串进行常规的回文测试.
您可以在此处详细了解正则表达式
小智 5
用于确定单词是否是回文结构的该代码可以更加简化.查找更新的代码
String word;
int z;
int y = 0;
int i = 0;
char letter;
Scanner input = new Scanner(System.in);
System.out.print("Enter a word: ");
word = input.nextLine();
word = word.replaceAll("\\s+", "");
word = word.toLowerCase();
z = word.length()-1;
while (i <= z){
if ((letter = word.charAt(i)) == (letter = word.charAt(z-i))){
y += 1;
}
i += 1;
}
if (y == (z+1)){
System.out.println("The word IS a palindrome");
}
else{
System.out.println("The word is NOT a palindrome");
}
}
}
Run Code Online (Sandbox Code Playgroud)
这看起来像一个很老的帖子,但我想我偶然发现了一个更简单的回文测试解决方案.这将检查第一个和最后一个字符并向内移动,并在字符不匹配时立即退出程序.
public class CharTest {
public static void main(String[] args) {
//converts string to lowercase and replaces everything except numbers
// and alphabets
String s = "Niagara. O roar again!".toLowerCase().replaceAll("\\W", "");
int j=0;
int k = s.length() - 1;
while(j < s.length() / 2) { //loops until half the length of the string if
//even and floor value if odd.
if (s.charAt(j++) != s.charAt(k--)){//check for first and last chars
//and go inwards. if char do not match print 'Not a Palindrome' and exit
System.out.println("Not a Palindrome");
System.exit(0);}
}
System.out.println("Palindrome"); //if every chars match print "Palindrome"
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36988 次 |
| 最近记录: |