我怎样才能打印特殊字符,但我仍然可以比较它是否是回文

How can I print the special character but still I can compare it if its a palindrome or not

import java.util.*;
public class Fin4 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        System.out.print("Enter a word to check if it is a palindrome: ");
        String word = in.nextLine();
        
        word = word.replaceAll("[{}!@#$%^&.,' ]", "");
        word = word.substring(0);
        String reverse = "";
        for(int i=word.length()-1;i>=0;i--)
            reverse+=word.charAt(i);
            
        if(word.equalsIgnoreCase(reverse))
            System.out.print(word + " is a palindrome.");
        else
            System.out.print(word + " is not a palindrome.");
    }
}

例如 输入单词查看是否回文:Madam, I'm adam 输出应该是 -> 女士,我是亚当是回文 但我的输出是 -> MadamImadam 是一个回文

您可以将原始单词的副本存储在一个变量中(例如 copyWord)并在打印语句中打印该变量。

未打印原始字符串的原因是您正在修改它并存储更新后的单词(在 word.replaceAll() 中)

public class Fin4 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter a word to check if it is a palindrome: ");
        String word = in.nextLine();
        String copyWord = word;
        word = word.replaceAll("[{}!@#$%^&.,' ]", "");
        word = word.substring(0);
        String reverse = "";
        for (int i = word.length() - 1; i >= 0; i--)
            reverse += word.charAt(i);

        if (word.equalsIgnoreCase(reverse))
            System.out.print(copyWord + " is a palindrome.");
        else
            System.out.print(copyWord + " is not a palindrome.");
    }
}

输出为

Enter a word to check if it is a palindrome: Madam, I'm adam
Madam, I'm adam is a palindrome.