【问题标题】:how to compare word letters using if statements? [closed]如何使用 if 语句比较单词字母? [关闭]
【发布时间】:2017-07-05 20:52:32
【问题描述】:

我正在尝试编写一个程序来读取一个单词并打印 if:

  • 以字母 y 结尾。

  • 首尾相同,忽略大小写。

这就是我目前所拥有的,但我很难想出一行代码来检查单个字母或比较第一个和最后一个字母。

  if (. . .)
  {
     System.out.println(word + " ends in a y");
  }

  if (. . .)
  {
     System.out.println(word + " starts and ends with the same letter");
  }      

【问题讨论】:

标签: java string if-statement charat


【解决方案1】:

String 有一个endsWith 方法。

if (word.endsWith("y") || word.endsWith("Y")) {
    System.out.println(word + " ends with y");
}

只要字符串不为空,您就可以使用charAt 从字符串中获取一个字符。您可以使用Character.toUpperCase 将字符转换为大写,这样您就可以比较字符而不必担心它们的大小写。

if (word.length() > 0 && Character.toUpperCase(word.charAt(0))==Character.toUpperCase(word.charAt(word.length()-1))) {
    System.out.println(word + " starts and ends with the same letter.");
}

【讨论】:

  • 谢谢,您的代码让事情变得更清晰了。
【解决方案2】:

您可以同时使用String.endsWith

// To ignore case, just lower all
word = word.toLowerCase();
// Check if it ends with 'y'
if (word.endsWith("y"))
// Check if it starts and ends with same letter
if (word.endsWith(word.substring(0,1)))

【讨论】:

  • 欢迎来到 Stack Overflow!虽然您可能已经解决了这个用户的问题,但纯代码的答案对于将来遇到这个问题的用户来说并不是很有帮助。请编辑您的答案以解释为什么您的代码解决了原始问题。
【解决方案3】:

在你的字符串中考虑一个单词 hello。您可以使用 word.length() 轻松获取单词长度,这将返回 5 表示“Hello”

使用另一种称为 charAt(int position) 的方法,您可以获得给定位置的字符。

System.out.println(String.valueOf(word.charAt(0))); //结果是H System.out.println(String.valueOf(word.charAt(4))); //结果是o

4 是单词的长度减一,因此请尝试以这种方式为所有单词动态查找它:

String.valueOf((word.length()-1))

如果你有两个字符串,你可以将它们与:

string1.equals(string2)

如果它们相同则返回 true,否则返回 false。

以下是完整的源代码:

    String word = "Hello";

    //no if is needed for the first one
    println(word + " ends with letter " + word.charAt(word.length()-1) + ".");


   if (String.valueOf(word.charAt(0)).equals(String.valueOf(word.charAt(word.length()-1)))) {
        println(word + " starts and ends with the same letter.");
    }

【讨论】:

  • 欢迎来到 Stack Overflow!虽然您可能已经解决了这个用户的问题,但纯代码的答案对于将来遇到这个问题的用户来说并不是很有帮助。请编辑您的答案以解释为什么您的代码解决了原始问题。
  • 我编辑了我的答案。我希望您改变主意并将我的回答标记为有用的解决方案。
  • 或许您应该尝试编译这段代码,然后解决问题。
猜你喜欢
  • 2020-08-01
  • 2014-03-03
  • 2018-07-10
  • 1970-01-01
  • 2016-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多