在一个单词的末尾计算y和z

xhe*_*nry 1 java

这就是问题:给定一个字符串,计算以'y'或'z'结尾的单词数 - 所以'heavy'中的'y'和'fez'中的'z'计数,但不是'y' 'in"yellow"(不区分大小写).如果没有紧跟在它后面的字母,我们会说ay或z在一个单词的末尾.(注意:Character.isLetter(char)测试char是否是字母.)

countYZ("fez day") ? 2
countYZ("day fez") ? 2
countYZ("day fyyyz") ? 2
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

public int countYZ(String str) {
  int count = 0;
  for (int i=0; i<str.length(); i++){
  if (Character.isLetter(i) && (Character.isLetter(i+1)==false || i+1==str.length()) && (Character.toLowerCase(str.charAt(i))=='y' || Character.toLowerCase(str.charAt(i))=='z')){
  count++;
  }
  }
  return count;
}
Run Code Online (Sandbox Code Playgroud)

我知道它很乱,但我只是想弄清楚它为什么现在不能正常工作.每次运行都返回"0".在if语句中,我正在检查:是我的信吗?是i + 1一个字母或字符串的结尾?最后,如果我是'y'或'z'.感谢帮助!

Tim*_*ker 5

你可以使用正则表达式:

public int countYZ(String str) {
    int count = 0;
    Pattern regex = Pattern.compile("[yz](?!\\p{L})", Pattern.CASE_INSENSITIVE);
    Matcher regexMatcher = regex.matcher(str);
    while (regexMatcher.find()) {
        count++;
    } 
    return count;
}
Run Code Online (Sandbox Code Playgroud)

说明:

[yz]      # Match the letter y or z
(?!\p{L}) # Assert that no letter follows after that
Run Code Online (Sandbox Code Playgroud)