我需要找出不同元音的数量。我想出了下面的代码,但它不能区分相同的元音:
public static int count_Vowels(String str) {
str = str.toLowerCase();
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u') {
count++;
}
}
return count;
}
最佳答案
我将从五个变量(每个元音一个)设置为 0
开始,迭代输入中的字符,如果我找到一个,则将相应的变量设置为 1
匹配,并简单地返回所述变量的累加值。喜欢,
public static int count_Vowels(String str) {
int a = 0, e = 0, i = 0, o = 0, u = 0;
for (char ch : str.toLowerCase().toCharArray()) {
if (ch == 'a') {
a = 1;
} else if (ch == 'e') {
e = 1;
} else if (ch == 'i') {
i = 1;
} else if (ch == 'o') {
o = 1;
} else if (ch == 'u') {
u = 1;
}
}
return a + e + i + o + u;
}
关于java - 打印字符串中唯一元音的数量,Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49038048/