📌  相关文章
📜  计算字符串中元音和辅音总数的Java程序

📅  最后修改于: 2022-05-13 01:55:05.862000             🧑  作者: Mango

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

给定一个字符串,计算这个给定字符串中元音和辅音的总数。假设 String 可能只包含特殊字符,或空格,或所有的组合。这个想法是迭代字符串并检查该字符是否存在于参考字符串中。如果某个字符出现在参考增量元音数中,则将元音数加 1,否则,将辅音数加 1。

例子:

Input : String = "GeeksforGeeks"
Output: Number of Vowels = 5
        Number of Consonants = 8

Input : String = "Alice"
Output: Number of Vowels = 3
        Number of Consonants = 2

方法:

  1. 创建两个变量 v 和 cons 并用 0 初始化它们。
  2. 开始字符串遍历。
  3. 如果第 i 个字符是元音,则将 v 变量增加 1。
  4. 否则,如果字符是辅音,则在 cons 变量中增加 1。

例子

Java
// Java Program to Count Total Number of Vowels
// and Consonants in a String
 
// Importing all utility classes
import java.util.*;
 
// Main class
class GFG {
   
     // Method 1
    // To prints number of vowels and consonants
    public static void count(String str)
    {
        // Initially initializing elements with zero
        // as till now we have not traversed 
        int vow = 0, con = 0;
       
        // Declaring a reference String
        // which contains all the vowels
        String ref = "aeiouAEIOU";
       
        for (int i = 0; i < str.length(); i++) {
             
            // Check for any special characters present
            // in the given string
            if ((str.charAt(i) >= 'A'
                 && str.charAt(i) <= 'Z')
                || (str.charAt(i) >= 'a'
                    && str.charAt(i) <= 'z')) {
                if (ref.indexOf(str.charAt(i)) != -1)
                    vow++;
                else
                    con++;
            }
        }
       
        // Print and display number of vowels and consonants
        // on console
        System.out.println("Number of Vowels = " + vow
                           + "\nNumber of Consonants = "
                           + con);
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Custom string as input
        String str = "#GeeksforGeeks";
       
        // Callin gthe method 1
        count(str);
    }
}


输出
Number of Vowels = 5
Number of Consonants = 8