示例: 计算元音、辅音、数字和空格的程序
class Main { public static void main(String[] args) { String line = "this website is aw3som3."; int vowels = 0, consonants = 0, digits = 0, spaces = 0; line = line.toLowerCase(); for (int i = 0; i < line.length(); ++i) { char ch = line.charAt(i); // check if character is any of a, e, i, o, u if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { ++vowels; } // check if character is in between a to z else if ((ch >= 'a' && ch <= 'z')) { ++consonants; } // check if character is in between 0 to 9 else if (ch >= '0' && ch <= '9') { ++digits; } // check if character is a white space else if (ch == ' ') { ++spaces; } } System.out.println("Vowels: " + vowels); System.out.println("Consonants: " + consonants); System.out.println("Digits: " + digits); System.out.println("White spaces: " + spaces); } }
输出
Vowels: 7 Consonants: 11 Digits: 2 White spaces: 3
在上面的示例中,我们为每个检查设置了 4 个条件。
第一个if
条件是检查字符是否为元音。
if
后面的else if
条件是检查字符是否为辅音。否则顺序应该相同,所有元音也被视为辅音。
第二个else if
是检查字符是否在0到9之间。
最后一个条件是检查字符是否为空格字符。
为此,我们使用
toLowerCase()
将行小写。这是一种优化,不检查大写的 A 到 Z 和元音。
我们使用
length()
函数来知道字符串的长度,并使用
charAt()
来获取给定索引(位置)处的字符。 >