Java教程

Java计算字符串中的元音和辅音的总数

在此程序中,我们的任务是计算给定字符串中存在的元音和辅音的总数。
我们知道,字母a,e,i,o,u被称为英语字母中的元音。除此之外的任何字符都称为辅音。
要解决此问题,首先,我们需要将字符串中的每个大写字母转换为小写字母,以便仅使用小写元音而不是大写字母进行比较元音,即(A,E,I,O,U)。然后,我们必须使用for或while循环遍历字符串,并将每个字符与所有元音匹配,即a,e,i,o,u。如果找到匹配项,则将count的值增加1,否则继续执行程序的正常流程。该程序的算法如下。

算法

步骤1: START 步骤2: 设置 vCount = 0,cCount = 0 步骤3: DEFINE string str ="This is a really simple sentence"。 步骤4: 将str转换为小写 步骤5: SET i = 0。 步骤6: 直到i < str.length()重复步骤6至步骤8 步骤7: : 如果str的任何字符与任何元音匹配,则
vCount = vCount +1。
步骤8: 如果除元音之外的任何字符位于a和z之间,则
cCount = cCount = + 1。
步骤9: i = i + 1 步骤10: 打印vCount。 步骤11: 打印cCount。 步骤12: END

程序:

public class CountVowelConsonant {
    public static void main(String[] args) {
        //Counter variable to store the count of vowels and consonant
        int vCount = 0, cCount = 0;
        //Declare a string
        String str = "this is a really simple sentence";
        //Converting entire string to lower case to reduce the comparisons
        str = str.toLowerCase();
        for(int i = 0; i < str.length(); i++) {
            //Checks whether a character is a vowel
            if(str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') {
                //Increments the vowel counter
                vCount++;
            }
            //Checks whether a character is a consonant
            else if(str.charAt(i) >
            = 'a' &
            &
            str.charAt(i)<='z') {
                //Increments the consonant counter
                cCount++;
            }
        }
        System.out.println("Number of vowels: " + vCount);
        System.out.println("Number of consonants: " + cCount);
    }
}
输出:
Number of vowels: 10
Number of consonants: 17
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4