我需要找到不同元音的数量.我想出了下面的代码,但它无法区分相同的元音:
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;
}
Run Code Online (Sandbox Code Playgroud)
我将从设置为的五个变量(每个元音一个)开始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;
}
Run Code Online (Sandbox Code Playgroud)