【问题标题】:Check if charAt are the same (case sensitive)检查 charAt 是否相同(区分大小写)
【发布时间】:2015-10-13 09:47:12
【问题描述】:

我必须编写一个方法来检查一个单词是否是回文。可能有比我更简单的方法,但这只是基于我到目前为止所学到的。我的方法有效,除非有大写字母与小写字母相比。

编辑:不是很清楚。我的方法返回大写和小写字母相同。但我想说它们是不同的

public static void printPalindrome(Scanner kb) {
System.out.print("Type one or more words: ");
String s = kb.nextLine();
int count = 0;
for(int i = 0; i < s.length();i++) {
    char a = s.charAt(i);
    char b = s.charAt(s.length()-(i+1));
    if (a==b) {
        count ++;
    } else {
        count = count;
    }
}
if (count == s.length()) {
    System.out.print(s + " is a palindrome!");
} else {
    System.out.print(s + " is not a palindrome.");
}
}

【问题讨论】:

  • 为什么要遍历整个字符串? i只需跑到中心即可。
  • 我刚刚测试了您的代码,它按照您说的方式运行。例如,“中午”不是回文。 See this 如果你真的得到了不同的结果,那么也许 Scanner 正在做一些不应该做的事情……不过我不知道

标签: java char compare equals palindrome


【解决方案1】:

我会推荐一种稍微不同的方法,我会使用 StringBuilder#reverse 反转字符串,然后使用 String#equalsIgnoreCase 比较两个字符串

String s = kb.nextLine();
StringBuilder sb = new StringBuilder(s).reverse();

if (s.equalsIgnoreCase(sb.toString())) {
...
} else {
...
}

【讨论】:

    【解决方案2】:

    您可以通过将输入字符串转换为大写来解决您的问题:

    String s = kb.nextLine().toUpperCase();
    

    或者,如果您希望保留原始字符串的大小写,请创建一个新字符串并测试它是否是回文。

    String s = kb.nextLine();
    String u = s.toUpperCase();
    int count = 0;
    for(int i = 0; i < u.length();i++) {
        char a = u.charAt(i);
        char b = u.charAt(u.length()-(i+1));
        if (a==b) {
            count ++;
        } else {
            count = count;
        }
    }
    

    【讨论】:

      【解决方案3】:

      我认为你可以用它的 ascii 值来做到这一点

      look this picture

      然后你应该将你的 char 转换为 ascii

      char character = 'a';
      int ascii = (int) character;
      

      然后比较整数

      【讨论】:

      • 你的答案如何解决大小写问题?
      猜你喜欢
      • 2010-11-27
      • 2020-10-21
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 2020-01-26
      • 2021-12-23
      • 2011-03-08
      • 2021-12-03
      相关资源
      最近更新 更多