[英]Java number of cons in a string, not working
I am trying to just find the number of consonants in a string. 我试图找到一个字符串中辅音的数量。 The following is the code I have for the method, but it keeps returning 0 when I run it.
以下是该方法的代码,但是在运行该方法时,它始终返回0。 Am I using the !
我在用! wrong?
错误? Do I need to do it for each individual case?
我是否需要针对每个案例进行处理? ie: !(ch == ('a')) ||
即:!(ch ==('a'))|| !(ch == ('o'))
!(ch ==('o'))
public int numCons() {
int i = 0;
int length = quote.length();
int con = 0;
String string;
for (i = 0; i < length; i++) {
//string = quote.substring(i);
char ch = quote.charAt(i);
if (!(ch == ('a') || ch == ('e') || ch == ('i')
|| ch == ('o') || ch == ('u') || ch == ('y') || ch == ('A')
|| ch == ('E') || ch == ('I') || ch == ('O') || ch == ('U') || ch == ('Y')))
if (Character.isLetter(i))
con++;
}
return con;
}
i
is the index you iterate over, not the character. i
是您要遍历的索引,而不是字符。 You probably meant check 你可能是要检查
if (Character.isLetter(ch))
by the way if you're using Java 8+ then you can do this in one line with use of Stream API: 顺便说一句,如果您使用的是Java 8+,则可以使用Stream API在一行中完成此操作:
quote.chars().filter(c -> !"aeiou".contains(String.valueOf((char) c).toLowerCase())).count();
(there's probably an even more elegant way, this was just the first thing i wrote) (可能有一种更优雅的方式,这只是我写的第一件事)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.